PHP json_decode JSON_ERROR_SYNTAX

时间:2017-09-21 18:47:23

标签: php json

我尝试从此link

加载和解析JSON文件

但我有ready问题和为JSON_ERROR_SYNTAX提供的无效参数。为什么会这样?

foreach()

[{ "Manufacturer": "Toyota", "Sold": 1200, "Month": "2012-11" }, { "Manufacturer": "Ford", "Sold": 1100, "Month": "2012-11" }, { "Manufacturer": "BMW", "Sold": 900, "Month": "2012-11" }, { "Manufacturer": "Benz", "Sold": 600, "Month": "2012-11" }, { "Manufacturer": "GMC", "Sold": 500, "Month": "2012-11" }, { "Manufacturer": "HUMMER", "Sold": 120, "Month": "2012-11" }]

1 个答案:

答案 0 :(得分:4)

您提供的link为UTF-8中的JSON提供字节顺序标记。显然json_decode()不能很好地处理这三个无关紧要的角色。解决方案是剥离BOM:

<?php

//see https://stackoverflow.com/a/32185872/500890
function removeBomUtf8($s){
   if(substr($s,0,3)==chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF'))){
        return substr($s,3);
    }else{
        return $s;
    }
}

$url = "http://www.pureexample.com/backend/data/car-sale.json";
$content = file_get_contents($url);
$clean_content = removeBomUtf8($content);
$decoded = json_decode($clean_content);

//Recovered data
echo "<pre>" . print_r($decoded, TRUE);

我采用这个解决方案剥离了BOM:https://stackoverflow.com/a/32185872/500890,虽然有很多它们在互联网上浮动。主要思想是剥离前三个特定字符,如果它们确实是一个BOM。