Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Library to convert JSON to CSV?

I've got a JSON service and need to create a script to export data to CSV files. Does anyone have a method or library you can suggest to migrate JSON to CSV format?

Here's an example format though I expect to have to retro-fit the solution to work with it:

{"service_name":
      { key : value, key : value....}
}

or:

{"service_name":
        [
               { key : value, key : value....},
               ...
         ]
}
like image 494
wajiw Avatar asked Mar 05 '12 20:03

wajiw


2 Answers

i generally agree with the commenters, but if you're data is prepared this way, isn't this pseudo-code all you need?

$json_str = "{'aintlist':[4,3,2,1], 'astringlist':['str1','str2']}";

$json_obj = json_decode ($json_str);

$fp = fopen('file.csv', 'w');

foreach ($json_obj as $fields) {
    fputcsv($fp, $fields);
}

fclose($fp);
like image 84
mindandmedia Avatar answered Sep 28 '22 20:09

mindandmedia


Something like this should work, assuming your JSON is an array of data sets without arrays or embedded objects:

$file = file_get_contents('http://example.com/blah/blah');
$json = json_decode($file);

$csvfile = fopen('file.csv', 'w+');
foreach ($json as $row) {
    $line = "'" . join("\",\"", $row) . "\"\n";
    fputs($csvfile, $line);
}
fclose($csvfile);

You'll have to add appropriate error handling. There are a lot of things that can go wrong when trying to do this sort of thing (i.e. JSON file not available or is malformatted, can't create new CSV file)

like image 25
curtisdf Avatar answered Sep 28 '22 20:09

curtisdf