Created
January 21, 2017 02:46
-
-
Save mkasberg/50b1ba1bfea5a5a793572cb6fed1af26 to your computer and use it in GitHub Desktop.
Converts a CSV to JSON array based on CSV headings.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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