使用PHP将JSON导出为CSV

The marketing app that we are using gives me the following JSON code that I want to export as a CSV File.

{"FirstName":"data","Surname":"data","E-mail Address":"data","PurchasedGoods":"data","Address1":"data","Address2":"data","City":"data","Postcode":"data","Company":"data","MiddleName":"data","Country":"data","Title":"data"}

There will be many records in the JSON code.

Please help me with the PHP code that can export the above JSON code/records to a CSV file.

I am using the below code at the moment:

<?php
$request = file_get_contents('php://input');
$req_dump = print_r($request, TRUE);
$fp = fopen('request.log', 'a');
$fp = fopen('file.csv', 'w');
fwrite($fp, $req_dump);
fclose($fp);
?>

I have also added the below code but no joy:

#!/usr/bin/php
<?php


if (empty($argv[1])) die("The json file name or URL is missed
");
$jsonFilename = $argv[1];

$json = file_get_contents($jsonFilename);
$array = json_decode($json, true);
$f = fopen('php://output', 'w');

$firstLineKeys = false;
foreach ($array as $line)
{
    if (empty($firstLineKeys))
    {
        $firstLineKeys = array_keys($line);
        fputcsv($f, $firstLineKeys);
        $firstLineKeys = array_flip($firstLineKeys);
    }
    // Using array_merge is important to maintain the order of keys acording to the first element
    fputcsv($f, array_merge($firstLineKeys, $line));
}
?>

Have a look on json_decode function to decode the json datas.

And for the CSV generation, you may form it "manually" (that's just writing in a file), but it's certainly better to use some existing librairies like one proposed by the League of Extraordinary Packages (what a name ! :) ) : http://csv.thephpleague.com/.

Hope that helps.