Skip to content

Instantly share code, notes, and snippets.

@instcode
Last active December 14, 2015 16:58
Show Gist options
  • Save instcode/5118761 to your computer and use it in GitHub Desktop.
Save instcode/5118761 to your computer and use it in GitHub Desktop.
JSON Text to CSV
$json_obj = json_decode($json, false);
ob_start();
$fp = fopen('php://output', 'w');
$header_included = false;
foreach ($json_obj as $lines) {
if ($header_included === false) {
fputcsv($fp, array_keys((array) $lines));
$header_included = true;
}
$line = array();
foreach ($lines as $key => $fields) {
$value = '';
if (is_array($fields)) {
$value = implode(',', $fields);
} else {
$value = $fields;
}
array_push($line, $value);
pg_raise('notice', $value);
}
fputcsv($fp, $line);
}
fclose($fp);
return ob_get_clean();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment