3

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

Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
Juanjo
  • 43
  • 4

2 Answers2

2

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.

Ujin
  • 36
  • 3
  • PERFECT Ujin ! THANKS! I can not give you a positive, not having enough reputation :( – Juanjo Dec 15 '15 at 22:51
  • @Juanjo You can accept the answer by clicking the check mark on the left of this item. This will give the user +15 reputation and I believe will give you +2. – Spencer Wieczorek Dec 15 '15 at 23:10
0

You have to pass in an array to fputcsv. Use this code:

fputcsv($fp,(array)$comment);

Brian Hanson
  • 193
  • 1
  • 1
  • 6