Skip to content

Instantly share code, notes, and snippets.

@calacitizen
Last active December 23, 2015 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calacitizen/6681795 to your computer and use it in GitHub Desktop.
Save calacitizen/6681795 to your computer and use it in GitHub Desktop.
CSV to json
<?php
/*
* Converts CSV to JSON
*/
header('Content-type: application/json');
$filePath = '';
$pathToCSV = '';
// Set your CSV feed
$feed = $pathToCSV';
// Arrays we'll use later
$keys = array();
$newArray = array();
// Function to convert CSV into associative array
function csvToArray($file, $delimiter) {
// if you have http authorization
// $context = stream_context_create(array(
// 'http' => array(
// 'header' => "Authorization: Basic " . base64_encode("user:password")
// )
//));
if (($handle = fopen($file, 'r', false, $context)) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 0, $delimiter, '"')) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $arr;
}
// function array_combine2($arr1, $arr2) {
// $count = min(count($arr1), count($arr2));
// return array_combine(array_slice($arr1, 0, $count), array_slice($arr2, 0, $count));
// }
// Do it
$data = csvToArray($feed, ';');
// Set number of elements (minus 1 because we shift off the first row)
$count = count($data) - 1;
//Use first row for names
$labels = array_shift($data);
foreach ($labels as $label) {
$keys[] = $label;
}
// Add Ids, just in case we want them later
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
// Bring it all together
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
// put on server as JSON file
if (file_put_contents($filePath, json_encode($newArray))) {
echo "ok";
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment