Skip to content

Instantly share code, notes, and snippets.

@clesauln
Created June 26, 2018 12:14
Show Gist options
  • Save clesauln/1ee469fcd2d301c391b72c9a122fbd0f to your computer and use it in GitHub Desktop.
Save clesauln/1ee469fcd2d301c391b72c9a122fbd0f to your computer and use it in GitHub Desktop.
json to csv for Point objects and properties
#!/usr/bin/php
<?php
/*
* Convert JSON file to CSV and output it.
*
* JSON should be an array of objects, dictionaries with simple data structure
* and the same keys in each object.
* The order of keys it took from the first element.
*
* Example:
* json:
* [
* { "key1": "value", "kye2": "value", "key3": "value" },
* { "key1": "value", "kye2": "value", "key3": "value" },
* { "key1": "value", "kye2": "value", "key3": "value" }
* ]
*
* The csv output: (keys will be used for first row):
* 1. key1, key2, key3
* 2. value, value, value
* 3. value, value, value
* 4. value, value, value
*
* Uses:
* json-to-csv.php file.json > file.csv
*/
if (empty($argv[1])) die("The json file name or URL is missed\n");
$jsonFilename = $argv[1];
$json = file_get_contents($jsonFilename);
$array = json_decode($json, true);
$f = fopen('php://output', 'w');
$firstLineKeys = false;
createLines($array,$f);
function strpos_array($haystack, $needles, $offset = 0) {
if (is_array($needles)) {
foreach ($needles as $needle) {
$pos = strpos_array($haystack, $needle);
if ($pos !== false) {
return $pos;
}
}
return false;
} else {
return strpos($haystack, $needles, $offset);
}
}
function createLines(array $lines, $f){
if (empty($firstLineKeys))
{
$firstLineKeys = array_keys($lines[0]);
//create keys for firstline//
foreach($firstLineKeys as $key) {
if($key == "geometry") {
$point = $lines[0][$key];
if($point["type"] == "Point"){
array_shift($firstLineKeys);
array_unshift($firstLineKeys,"lat");
array_unshift($firstLineKeys,"lon");
array_pop($firstLineKeys);
array_splice($firstLineKeys, 2);
}
}
if($key == "properties") {
$props = $lines[0][$key];
$keys = array_keys($props);
foreach($keys as $prop){
array_push($firstLineKeys,$prop);
}
}
}
fputcsv($f, $firstLineKeys);
}
$val = [];
foreach($lines as $row){
$point = $row["geometry"]["coordinates"];
$lat = $point[1];
$lon = $point[0];
array_push($val,$lon);
array_push($val,$lat);
$props = $row["properties"];
foreach($props as $prop){
if(gettype($prop) !== "array"){
array_push($val,$prop);
}
}
fputcsv($f,$val);
$val =[];
}
// // Using array_merge is important to maintain the order of keys acording to the first element
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment