Search code examples
phpjsonforeachfputcsv

JSON Array Export to CSV in PHP


I'm trying to export to csv, a JSON with the following format:

$json_file2{
            "errors":
                    {
                    "code":0,
                    "text":""
                    },
            "results":
                    {
                    "resultado":
                    [
                        {
                        "referencia":"00000",
                        "cantidad":"24",
                        "cantidad_proveedor":null,
                        "delivery_time":"delivery time 2 days"
                        },
                        {
                        "referencia":"00001",
                        "cantidad":"24",
                        "cantidad_proveedor":"48",
                        "delivery_time":""
                        },
                        {
                        "referencia":"00098_1",
                        "cantidad":"96",
                        "cantidad_proveedor":null,
                        "delivery_time":"delivery time 4 days"
                        }
                    ]
                }
            }

I need to export to csv

"referencia":"00000",
"cantidad":"24",
"cantidad_proveedor":null,
"delivery_time":"delivery time 2 days"

in this format:

"00000","24",null,"delivery time 2 days"
"00001","24","48",""
"00098_1","96",null,"delivery time 4 days"
......

I try to do as I am learning

$decoded = json_decode($json_file2);
$comments = $decoded->data[0]->results->resultado;
$fp = fopen('stock2.csv', 'w');
foreach($comments as $comment){
   fputcsv($fp,$comment);
}

but always it gives me error foreach: Warning: Invalid argument supplied for foreach()

Where am I doing wrong? Tanks


Solution

  • There is no data array field in $json_file2. You have to use $decoded->results->resultado instead. And cast $comment as array as Brian says.

    Final code look like this:

    $decoded = json_decode($json_file2);
    $comments = $decoded->results->resultado;
    $fp = fopen('stock2.csv', 'w');
    foreach($comments as $comment) {
        fputcsv($fp, (array)$comment);
    }
    

    With that change you will get something like that:

    00000,24,,"delivery time 2 days"
    00001,24,48,
    00098_1,96,,"delivery time 4 days"
    

    Maybe you should write your own fputcsv function to achive the result you wish, with null and numbers with quotes.