Skip to content

Instantly share code, notes, and snippets.

@omundy
Last active October 25, 2017 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save omundy/fa769b835cca4253ceec534c245989db to your computer and use it in GitHub Desktop.
Save omundy/fa769b835cca4253ceec534c245989db to your computer and use it in GitHub Desktop.
Convert a Google Takeout JSON file to CSV table format
<?php
/**
* Convert a Google Takeout JSON file to CSV table format
* @author Owen Mundy owenmundy.com
* Note: Make sure PHP has enough memory allotted on your system to handle large strings
* Instructions:
* 1. Download PHP file and place next to your JSON file
* 2. Rename string pointing to your data file
* 3. On command line run $ php index.php
*/
// get the contents of your JSON file
// rename string to point to your data file
$json = file_get_contents("data.json");
// convert to PHP object/array
$obj = json_decode($json, true);
// access specific data inside object
$locations = $obj['locations'];
// create string to hold finished CSV
$csv = "";
// add header to CSV
$csv += "data,latitudeE7,longitudeE7,accuracy,altitude\n";
// for testing (provides early exit for testing code on large data files)
$test = 0;
$limit = 0;
// loop through the PHP object
foreach ($locations as $key => $location) {
// create temp var to hold current row
$loc = "";
// add data to row, with comma after each column...
// add date, converting from timestamp (milliseconds) to human-readable date
$loc .= date('Y-m-d H:i:s -0400', $location['timestampMs']/1000) .",";
// add lat/lng
$loc .= $location['latitudeE7'] .",";
$loc .= $location['longitudeE7'] .",";
// if accuracy and altitude are set then add, otherwise add empty string (comma)
if (isset($location['accuracy']))
$loc .= $location['accuracy'] .",";
else
$loc .= ",";
if (isset($location['altitude']))
$loc .= $location['altitude'] ."\n";
else
$loc .= "\n";
// add this row to CSV
$csv .= $loc;
// for testing, if $limit defined and $test > $limit then stop
if ($limit > 0 && ++$test > $limit)
die($csv);
}
// print the CSV to terminal
print $csv ."\n";
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment