JSON数组在PHP中导出为CSV

时间:2015-12-15 19:59:24

标签: php json foreach fputcsv

我尝试导出到csv,这是一种具有以下格式的JSON:

$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"
                        }
                    ]
                }
            }

$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" } ] } }

我需要导出到csv

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

采用以下格式: "referencia":"00000", "cantidad":"24", "cantidad_proveedor":null, "delivery_time":"delivery time 2 days"

我正在努力学习

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

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

但它总是给我错误的foreach: 警告:为foreach()提供的参数无效

我在哪里做错了? 罐

2 个答案:

答案 0 :(得分:2)

$ json_file2中有无数据数组字段。 您必须使用 $ decoding-> results-> resultado 。并且像Brian说的那样将 $ comment 强制为数组

最终代码如下:

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

通过这种改变,你会得到类似的东西:

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

也许你应该写你自己的fputcsv 函数来获得你想要的结果,使用null和带引号的数字。

答案 1 :(得分:0)

您必须将数组传递给fputcsv。使用此代码:

fputcsv($ FP,(数组)$评论);