【问题标题】:Convert json to csv using php使用php将json转换为csv
【发布时间】:2017-03-14 11:49:38
【问题描述】:

您好,我在将 json 转换为 csv 时遇到了小问题。 这是我的代码:

$jsonString = '{"cod":"200","calctime":0.3107,"cnt":15,"list":[{"id":2208791,"name":"Yafran","coord":{"lon":12.52859,"lat":32.06329},"main":{"temp":9.68,"temp_min":9.681,"temp_max":9.681,"pressure":961.02,"sea_level":1036.82,"grnd_level":961.02,"humidity":85},"dt":1485784982,"wind":{"speed":3.96,"deg":356.5},"rain":{"3h":0.255},"clouds":{"all":88},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]}]}';

//Decode the JSON and convert it into an associative array.
$jsonDecoded = json_decode($jsonString, true);

//Give our CSV file a name.
$csvFileName = 'file.csv';

//Open file pointer.
$fp = fopen($csvFileName, 'w');

//Loop through the associative array.
foreach($jsonDecoded as $row){
    //Write the row to the CSV file.
    fputcsv($fp, $row);
}

//Finally, close the file pointer.
fclose($fp);

?>

我尝试过使用像 [{"name":"Wayne","age":28},{"name":"John","age":21},{"name":"Sara","age":24}] 这样的另一种 json 格式,它的工作非常完美。 如何修改我的代码以正确保存为 csv 格式。

图片: 现在它像这样保存它: 我需要这样保存:

有人可以帮我吗?

【问题讨论】:

标签: php json csv


【解决方案1】:

希望这会奏效..

<?php

$jsonString = '{"cod":"200","calctime":0.3107,"cnt":15,"list":[{"id":2208791,"name":"Yafran","coord":{"lon":12.52859,"lat":32.06329},"main":{"temp":9.68,"temp_min":9.681,"temp_max":9.681,"pressure":961.02,"sea_level":1036.82,"grnd_level":961.02,"humidity":85},"dt":1485784982,"wind":{"speed":3.96,"deg":356.5},"rain":{"3h":0.255},"clouds":{"all":88},"weather":[{"id":500,"main":"Rain","description":"light rain","icon":"10d"}]}]}';

$jsonDecoded = json_decode($jsonString, true);
$csvHeader=array();
$csvData=array();
jsontocsv($jsonDecoded);
print_r($csvHeader);
print_r($csvData);



$csvFileName = 'file.csv';
$fp = fopen($csvFileName, 'w');
fputcsv($fp, $csvHeader);
fputcsv($fp, $csvData);
fclose($fp);

function jsontocsv($data)
{
    global $csvData,$csvHeader;
    foreach($data as $key => $value)
    {
        if(!is_array($value))
        {
            $csvData[]=$value;
            $csvHeader[]=$key;
        }
        else 
        {
            jsontocsv($value);
        }
    }
}

json 2

<?php

$jsonString =file_get_contents("http://samples.openweathermap.org/data/2.5/box/city?bbox=12,32,15,37,10&appid=b1b15e88fa797225412429c1c50c122a1");;
$jsonDecoded = json_decode($jsonString, true);
$csvHeader=array();
$csvData=array();
$csvFileName = 'file.csv';
$fp = fopen($csvFileName, 'w');
$counter=0;
foreach($jsonDecoded["list"] as $key => $value)
{
    jsontocsv($value);
    if($counter==0)
    {
        fputcsv($fp, $csvHeader);
        $counter++;
    }
    fputcsv($fp, $csvData);
    $csvData=array();
}
fclose($fp);

function jsontocsv($data)
{
    global $csvData,$csvHeader;
    foreach($data as $key => $value)
    {
        if(!is_array($value))
        {
            $csvData[]=$value;
            $csvHeader[]=$key;
        }
        else 
        {
            jsontocsv($value);
        }
    }
}

【讨论】:

  • 请不要在场外发布答案。它们对 SO 的未来访问者有何用处
  • 这很好用谢谢!!但是如果我们像这样使用 json 为什么不起作用:samples.openweathermap.org/data/2.5/box/…
  • @GeorgiBangeev 我已经根据该问题给出了答案,但是您所指的 json 包含多行和嵌套数据,这些数据无法通过此代码完成。我正在为那个特定的 json 更新我的帖子。
【解决方案2】:

试试这个:

$rowNr = 0;
$prevKey = "";
$target = [];

$iterator = new RecursiveArrayIterator($jsonDecoded['list'][$rowNr]);
iterator_apply($iterator, 'traverseStructure', array($iterator,$prevKey,&$target));

function traverseStructure($iterator, $prevKey, &$target) {

while ( $iterator -> valid() ) {
    if ( $iterator -> hasChildren() ) {         
        $prevKey = $iterator->key();
        traverseStructure($iterator -> getChildren(), $prevKey, $target);            
    }
    else {                       
        if(isset($prevKey) && !is_int($prevKey)){               
            $row1 = $prevKey."/".$iterator->key();              
        }else{
            $row1 = $iterator->key();
        }           
        $row2 = $iterator->current();           
        $target[$row1] = $row2;         
    }
    $iterator -> next();        
   }
}

fputcsv($fp, array_keys($target));
fputcsv($fp, array_values($target));

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 2018-01-22
    • 1970-01-01
    • 2015-08-23
    • 2016-03-18
    • 2012-03-23
    • 2022-06-13
    • 1970-01-01
    相关资源
    最近更新 更多