Skip to content

Instantly share code, notes, and snippets.

@sumpygump
Created May 21, 2015 17:17
Show Gist options
  • Save sumpygump/9fddf6c2803b29451204 to your computer and use it in GitHub Desktop.
Save sumpygump/9fddf6c2803b29451204 to your computer and use it in GitHub Desktop.
An example PHP script of converting a specific data set from CSV into a specific JSON format. Used as an example of the process of handling this type of data transformation.
#!/usr/bin/env php
<?php
/**
* This script is used to convert a CSV file
* into json format
*
* Run it from the command line like so:
* $ ./csv-to-json data.csv > data.json
*/
if (!isset($argv[1])) {
print "Missing parameter\n";
exit(1);
}
$file = $argv[1];
if (!file_exists($file)) {
printf("File '%s' not found or not readable.\n", $file);
exit(2);
}
$data = csv_to_array($file);
$persons = array();
foreach ($data as $row) {
$person = new StdClass();
if (!isset($row['First Name'])) {
continue;
}
$person->name = $row['First Name'] . ' ' . $row['Last Name'];
$person->date = $row['Date'];
$person->age = $row['Age'];
$person->pizza_topping = $row['Pizza Topping'];
$persons[] = $person;
}
$personRegistry = new StdClass();
$personRegistry->hash = '';
$personRegistry->date = date('Y-m-d H:i:s');
$personRegistry->persons = new StdClass();
$p = $personRegistry->persons;
foreach ($persons as $person) {
$p->{$person->name} = new StdClass();
$p->{$person->name}->{$person->date} = $person;
}
// Make the entire registry into a string so we can give it a unique hash
$registryString = json_encode($personRegistry);
$registryHash = md5($registryString);
// Save the hash to the object
$personRegistry->hash = $registryHash;
// Output the registry
print(json_encode($personRegistry, JSON_PRETTY_PRINT));
/**
* Convert a comma separated file into an associated array.
* The first row should contain the array keys.
*
* Example:
*
* @param string $filename Path to the CSV file
* @param string $delimiter The separator used in the file
* @return array
* @link http://gist.github.com/385876
* @author Jay Williams <http://myd3.com/>
* @copyright Copyright (c) 2010, Jay Williams
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
First Name Last Name Date Age Pizza Topping
Justin Bailey 2014-09-21 25 Onion
Ricky Martin 2013-05-14 22 Cheese
Sarah Connor 2015-01-28 31 Artichoke Hearts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment