gpt4 book ai didi

PHP json_解码 JSON_ERROR_SYNTAX

转载 作者:行者123 更新时间:2023-12-05 01:18:13 32 4
gpt4 key购买 nike

我尝试从这个 link 加载和解析 JSON 文件

但我有 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" }]

<?php
$url = "http://www.pureexample.com/backend/data/car-sale.json";
$url = file_get_contents($url);
print_r($url);
$url = stripslashes($url);
print_r($url);
$url = str_replace("\n", "", $url);
print_r($url);
$url = iconv('UTF-8', 'UTF-8//IGNORE', utf8_encode($url));
print_r($url);
$url = json_decode($url, true);
// Add this switch to your code
switch (json_last_error())
{
case JSON_ERROR_NONE:
echo ' - No errors';
break;
case JSON_ERROR_DEPTH:
echo ' - Maximum stack depth exceeded';
break;
case JSON_ERROR_STATE_MISMATCH:
echo ' - Underflow or the modes mismatch';
break;
case JSON_ERROR_CTRL_CHAR:
echo ' - Unexpected control character found';
break;
case JSON_ERROR_SYNTAX:
echo ' - Syntax error, malformed JSON';
break;
case JSON_ERROR_UTF8:
echo ' - Malformed UTF-8 characters, possibly incorrectly encoded';
break;
default:
echo ' - Unknown error';
break;
}


foreach($koyim as $data){
echo $data['Manufacturer'];
echo $data['Sold'];
echo $data['Month'];
echo "<br/>";
}
?>

最佳答案

link您提供的 JSON 以 UTF-8 格式提供,并带有字节顺序标记。显然 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。

关于PHP json_解码 JSON_ERROR_SYNTAX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46351165/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com