用于将Json转换为CSV的PHP脚本

时间:2014-03-15 21:09:52

标签: php json csv

我有一个API JSON服务,需要创建一个脚本来将数据导出到CSV文件。 有没有人有PHP脚本将JSON迁移到CSV格式?

示例Json文件

  {"packWidth":200,
  "itemNo":"SEH404",
  "groupItemNo":"SEH404",
  "status":1,
  "categoryId":24356,
  "packType":"ColorBox",
  "barcode":"1234567890987",
  "modelLabel":"Color",
  "modelList":[{"key":"SEH404","value":"Black"},{"key":"SEH404W","value":"White"}],
  "packQty":20,
  "packInclude":"USB Adapter, USB Charger, Earphone, Leather Case",
  "id":3456}

一个重要的部分是带有标签" modelList"

的数组

数组modelList的结果必须是每个值的列

示例:

packWidth,itemNo,groupItemNo,status,categoryId,packType,barcode,modelLabel,modelList1,modelList2,packQty,packInclude,id

200,SEH404,SEH404,1,24356,ColorBox,1234567890987,颜色, SEH404:黑色,SEH404W:白色,20,USB适配器......,3456

某些产品还可能包含5个记录" modelList1-modelList2 modelList3-modelList4-modelList5。没有modelList的产品会将modelList记录为空。

2 个答案:

答案 0 :(得分:0)

请试试这个。 假设$ json是原始数据,所以我在开始时解码它。

$json = json_decode($json);

// Will use $csv to build our CSV content
$csv = array();

// Need to define the special column
$modelList = 'modelList';

// Find necessary additional column number for modelList
$maxSubData = 0;
foreach ($json as $id => $data)
{
    $maxSubData = max(array(count($data->modelList), $maxSubData ));
}

// Headers for CSV file
// Headers Start
$headers = array();
foreach ($json[0] as $key => $value)
{
    if ($key == $modelList)
    {
        for ($i = 1; $i <= $maxSubData; $i++)
        {
            $headers[] = $modelList . $i;
        }
    }
    else
    {
        $headers[] = $key;
    }
}
$csv[] = '"' . implode('","', $headers) . '"';
// Headers End

// Now the rows
// Rows Start
foreach ($json as $data)
{
    $fieldValues = array();
    foreach ($data as $key => $value )
    {
        if ($key == $modelList)
        {
            $j = 0;
            foreach ($value as $subValue)
            {
                $subData = array();
                foreach ($subValue as $subCols)
                {
                    $subData[] = $subCols;
                }
                $j++;
                $fieldValues[] = htmlspecialchars(implode(':', $subData ));
            }
            for ($i = $j + 1; $i <= $maxSubData; $i++)
            {
                $fieldValues[] = '';
            }
        }
        else
        {
            $fieldValues[] = htmlspecialchars($value);
        }
    }

    $csv[] = '"' . implode('","', $fieldValues) . '"';
}
// Rows End

$finalCSV = implode("\n", $csv);

print $finalCSV;

答案 1 :(得分:-1)

这是不可能的,因为在JSON中你有分层数据结构,但CSV只是二维的(参见modelList属性)。