Skip to content

Instantly share code, notes, and snippets.

@hawkidoki
Last active May 8, 2018 16:24
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 hawkidoki/909fd331fe2d4e1804706f441e9b5db9 to your computer and use it in GitHub Desktop.
Save hawkidoki/909fd331fe2d4e1804706f441e9b5db9 to your computer and use it in GitHub Desktop.
<?php
function hwk_the_json_to_csv($json, $delimiter = ';'){
echo hwk_get_json_to_csv($json, $delimiter);
}
function hwk_get_json_to_csv($json, $delimiter = ';'){
$data = json_decode($json, true);
if(!is_array($data) || empty($data))
return;
$ouput = fopen('php://output', 'w');
$firstline = false;
ob_start();
foreach($data as $line){
if(empty($firstline)){
$firstline = array_keys($line);
fputcsv($ouput, $firstline, $delimiter);
$firstline = array_flip($firstline);
}
fputcsv($ouput, array_merge($firstline, $line), $delimiter);
}
return ob_get_clean();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment