首页 文章

使用PHP解析其中包含JSON的CSV

提问于
浏览
1

Introduction

我有一个CSV文件,其中每个字段都附有双引号( " ) . 每行中的最后一个字段是JSON字符串表示 . 我想编写一个解析CSV文件的PHP脚本,然后解析JSON字符串 . 这就是我现在拥有的 .

while (($line = fgetcsv($handle, 1000000, ";", '"')) !== false)
{
    // Another loop to loop over the fields
    // ...
    parse_json(end($line));
}

private function parse_json($json_string)
{
    if (!empty($json_string))
    {
        $json = json_decode($json_string, true);
        $msg = sprintf("The following description is not in proper JSON format: %s", $json_string);
        if (is_null($json))
        {
            // The function json_decode returns null if the string is not properly JSON formatted.
            throw new Exception($msg);
        }
    }
}

使用CSV文件中的以下行,我在PHP中获得以下数组 .

"A";"B";"C";"D";"E";;"{""Name"":""Richard B Mephisto""}"
array ('Name' => 'Richard B Mephisto');

Problem description

当我想在JSON字符串的一个值中允许双引号时,麻烦就开始了 . 对于JSON,我需要使用反斜杠转义双引号,而对于CSV,我需要使用另一个双引号来转义双引号 . 如果我想要以下数组,CSV文件和解析器应该如何?

array ('Name' => 'Richard "B" Mephisto');

Failed attempts

1)在CSV文件中使用以下行 .

"A";"B";"C";"D";"E";;"{""Name"":""""Richard B Mephisto""""}"

在解析JSON时,在调用 json_decode 之前,将每个 "" 替换为 /" . 这适用于这种情况,但我还需要允许空字符串 .

"A";"B";"C";"D";"E";;"{""Name"":""}"

这些也将被这个解决方案所取代 .

2)在CSV文件中使用反斜杠 . 原则上,JSON字符串应如下所示:

{"Name": "Richard \"B\" Mephisto"}

所以我在CSV文件中尝试这个:

"A";"B";"C";"D";"E";;"{""Name"":\""Richard B Mephisto\""}"

结果如下:

以下描述不是正确的JSON格式:{“JSON_key”:“Richard \”B \“”Mephisto“”}“

不知何故,它与转义字符和双引号一起无法正常工作 .

3)转义CSV中的反斜杠 .

"A";"B";"C";"D";"E";;"{""JSON_key"":""Richard \\""B\\"" Mephisto""}"

结果:

The following description is not in proper JSON format: {"JSON_key":"Richard \\"B\\" Mephisto"}

1 回答

  • 1

    试试这个:

    $in = '"A";"B";"C";"D";"E";;"{""Name"":""Richard \""B\"" Mephisto""}";"{""Name"":""""}"';
    $out = str_getcsv($in, ';', '"', '"'); 
    var_dump($out);
    

    结果:

    array(8) {
      [0]=>
      string(1) "A"
      [1]=>
      string(1) "B"
      [2]=>
      string(1) "C"
      [3]=>
      string(1) "D"
      [4]=>
      string(1) "E"
      [5]=>
      string(0) ""
      [6]=>
      string(33) "{"Name":"Richard \"B\" Mephisto"}"
      [7]=>
      string(11) "{"Name":""}"
    }
    

相关问题