Skip to content

Instantly share code, notes, and snippets.

@mkasberg
Created January 21, 2017 02:46
Show Gist options
  • Save mkasberg/50b1ba1bfea5a5a793572cb6fed1af26 to your computer and use it in GitHub Desktop.
Save mkasberg/50b1ba1bfea5a5a793572cb6fed1af26 to your computer and use it in GitHub Desktop.
Converts a CSV to JSON array based on CSV headings.
#!/usr/bin/env php
<?php
print "CSV 2 JSON\n";
if (!isset($argv[2])) {
print "Usage: csv2json.php infile.csv outfile.json\n";
exit();
}
$infile = $argv[1];
$outfile = $argv[2];
$hIn = fopen($infile, 'r');
$aCols = fgetcsv($hIn);
$aCols = array_map("strtolower", $aCols);
$aCols = array_map("trim", $aCols);
$aResult = array();
while($aLine = fgetcsv($hIn)) {
$aItem = array();
foreach($aCols as $iIndex => $strCol) {
$aItem[$strCol] = trim($aLine[$iIndex]);
}
$aResult[] = $aItem;
}
fclose($hIn);
$strResult = json_encode($aResult);
file_put_contents($outfile, $strResult);
print "Converted to JSON successfully!\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment