在PHP中将Json数组导出为CSV

时间:2015-12-17 18:59:23

标签: php json fputcsv

我有这个提供者数组

[
    {
        "reference":"01042",
        "images":   [
            "http:\/\/static1.provider.com\/34\/01042.jpg"
        ]
    },
    {
        "reference":"01057",
        "images":[
            "http:\/\/static1.provider.com\/57\/01057.jpg",
            "http:\/\/static3.provider.com\/58\/01057.jpg",
            "http:\/\/static2.provider.com\/59\/01057.jpg"]
    },
    ...
]

我使用以下代码导出

$json_file2 = file_get_contents('http://direct.provider.com/public/ref_urlimage_20.json', false);

$decoded = json_decode($json_file2);

$fp = fopen('imagenes.csv', 'w');
foreach($decoded as $comment) {
    fputcsv($fp, $comment);
}
fclose($fp);

但它显示了以下结果

01104,Array
01119,Array
40460,Array
00311,Array
00312,Array
00307,Array

何时需要导出为此格式

01104,http://static3.provider.com/155/01119.jpg
01119,http://static3.provider.com/155/04519.jpg,http://static3.provider.com/155/01148.jpg,http://static3.provider.com/155/0859.jpg
40460,http://static3.provider.com/155/01119.jpg,http://static3.provider.com/155/01118.jpg
00351,http://static3.provider.com/175/07219.jpg
...

我在哪里做错了? 感谢

1 个答案:

答案 0 :(得分:0)

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

$json = file_get_contents($jsonFilename);
$array = json_decode($json, true);
$f = fopen('output.csv', 'w');

$firstLineKeys = false;
foreach ($array as $line)
{
    if (empty($firstLineKeys))
    {
        $firstLineKeys = array_keys($line);
        fputcsv($f, $firstLineKeys);
        $firstLineKeys = array_flip($firstLineKeys);
    }
    $line_array = array($line['reference']);
    foreach ($line['images'] as $value)
    {
        $line_array.push($value);
    }
    fputcsv($f, $line_array);

}

因为你有像上面的代码一样的循环代码可能有助于解决问题

尝试使用以下代码

<?php
//if (empty($argv[1])) die("The json file name or URL is missed\n");
//$jsonFilename = $argv[1];
//
//$json = file_get_contents($jsonFilename);
$json_file2 = file_get_contents('http://direct.funidelia.es/public/ref_urlimage_20.json', false);
error_reporting(E_ALL);
//echo $json_file2;die;
    $json='{"data":'.$json_file2.'}';
//echo $json;
$array = json_decode($json, true);
//echo "<pre>";
//print_r($array);
//die;
$f = fopen('output.csv', 'w');

$firstLineKeys = false;
foreach ($array["data"] as $line)
{
//    echo "<pre>";
//    print_r($line);
//    die;
    if (empty($firstLineKeys))
    {
        $firstLineKeys = array_keys($line);
        fputcsv($f, $firstLineKeys);
        $firstLineKeys = array_flip($firstLineKeys);
    }
    $line_array = array($line['reference']);

    foreach ($line['images'] as $value)
    {
        array_push($line_array,$value);
    }
    fputcsv($f, $line_array);

}
echo "Success";
?>