Skip to content

Instantly share code, notes, and snippets.

@webmasterkai
Last active December 10, 2015 07:38
Show Gist options
  • Save webmasterkai/4402040 to your computer and use it in GitHub Desktop.
Save webmasterkai/4402040 to your computer and use it in GitHub Desktop.
convert schools csv to individual json files
<?php
/**
* Place this file in the same directory as the csv. PHP must be available to the local machine cli.
* $ php schools.csv-json.php
*/
// Assumes csv file is in the same directory.
define("FILENAME", "schools.csv");
$handle = fopen(FILENAME, 'r');
$processed = 0;
$schools = array();
if ($handle) {
$headers = explode(",", rtrim(fgets($handle, 4096), "\n"));
while (!feof($handle)) {
$buffer = fgets($handle, 4096);
$processed++;
$line = explode(',', $buffer);
if (empty($headers) || empty($line) || (count($headers) != count($line))) {
echo "Issue with line " . $processed . "\n";
continue;
}
$record = array_combine($headers, $line);
$id = $record['NCESSCH'];
$mzip = $record['MZIP'];
$zip = $record['LZIP'];
$name = strtolower($record['SCHNAM']);
$find = array('elem ', ' sch');
$replace = array('elementry ', ' school');
$name = ucwords(str_replace($find, $replace, $name));
$school = array(
'value' => $id,
'label' => $name,
'desc' => ucwords(strtolower($record['LSTREE'])) . ',' . ucwords(strtolower($record['LCITY'])),
);
if ($id) {
$schools[$zip][$id] = $school;
if ($zip != $mzip) {
$schools[$mzip][$id] = $school;
}
}
}
fclose($handle);
}
foreach ($schools as $zip => $school) {
$file_name = 'json/' . $zip . ".json";
file_put_contents($file_name, json_encode($school));
echo print_r($school);
}
$zips = array_keys($schools);
$file_name = 'json/zips.json';
file_put_contents($file_name, json_encode($zips));
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment