<?php
header('Content-type: application/json');
 

 
// Function to convert CSV into associative array
function csvToArray($file, $delimiter) { 
  if (($handle = fopen($file, 'r')) !== FALSE) { 
    $i = 0; 
    while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) { 
      for ($j = 0; $j < count($lineArray); $j++) { 
        $arr[$i][$j] = $lineArray[$j]; 
      } 
      $i++; 
    } 
    fclose($handle); 
  } 
  return $arr; 
} 
 
function formatArray ($feed) {

  $keys = array();
  $newArray = array();
  $data = csvToArray($feed, ',');
 
  $count = count($data) - 1;
 
  $labels = array_shift($data);  
 
  foreach ($labels as $label) {
    $keys[] = $label;
  }
 
  $keys[] = 'id';
 
  for ($i = 0; $i < $count; $i++) {
    $data[$i][] = $i;
  }
 
  for ($j = 0; $j < $count; $j++) {
    $d = array_combine($keys, $data[$j]);
    $newArray[$j] = $d;
  }

  return $newArray;

}
 
$feed = 'https://docs.google.com/spreadsheets/d/e/2PACX-1vQUspPunAmkZrtfhMgMvGYGTK_4ONsCnSoe6OcTFc-4ILRHTatdPIwgRx1eRM1qFTkYFMrvcx8OI4cv/pub?output=csv';

$data = formatArray($feed);

$info = json_encode($data);

$infoAsJson = json_decode($info);



$handle = fopen("renglones.json", 'w');
fwrite($handle, $info);



for ($i = 0; $i < count($infoAsJson); $i++) {
  $renglon = formatArray($infoAsJson[$i]->Link);
  $renglonInfo = json_encode($renglon);
  $renglonAsJson = json_decode($renglonInfo);
  
  $my_file = $infoAsJson[$i]->Renglones . ".json";
  $handle = fopen($my_file, 'w') or die ('Cannot open file');
  fwrite($handle, $renglonInfo);

}

?>
