[英]json_decode - returning NULL
下面的JSON字符串正在传递到json_decode()
,并且它返回NULL
。
{"total_goals":26,"total_games":17,"average_goals":"1.53"}
这是我的代码:
$homeJSON = file_get_contents("http://strategy-bets.com/archive/archive.php?baseurl=http://www.totalcorner.com".$Home_Team_Link);
$homeJSON = str_replace("\xEF\xBB\xBF",'',$homeJSON);
$homeJSON = rtrim($homeJSON);
$homeJSON = html_entity_decode($homeJSON);
$homeJSON = preg_replace('/\s+/', '', $homeJSON);
$clean = rtrim($homeJSON, "\x00..\x1F");
$home_decoded = json_decode($clean);
$home_decoded
仍然为NULL
。
首先,由于错误情况, json_decode()
返回NULL
。 您可以使用json_last_error()
确定错误条件的性质,该函数返回一个表示错误类型的整数常量。 您可以使用此功能(根据json_last_error()
手册页上描述的错误代码构建)对这些内容进行解码:
<?php
function decodeJsonError($errorCode)
{
$errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters, possibly incorrectly encoded',
JSON_ERROR_RECURSION => 'One or more recursive references in the value to be encoded',
JSON_ERROR_INF_OR_NAN => 'One or more NAN or INF values in the value to be encoded',
JSON_ERROR_UNSUPPORTED_TYPE => 'A value of a type that cannot be encoded was given'
);
if (isset($errors[$errorCode]))
{
return $errors[$errorCode];
}
return 'Unknown error';
}
现在,由于无法提供有效的链接(我知道这可能是敏感数据),所以我无法确切知道返回了您正在调用的API,但是,让我们尝试另一种方法,然后尝试仅从返回的API中提取JSON :
<?php
$homeJSON = file_get_contents("http://strategy-bets.com/archive/archive.php?baseurl=http://www.totalcorner.com".$Home_Team_Link);
if (!preg_match('/(\{"[^\}]+\})/', $homeJSON, $matches))
{
echo "An error occurred; no JSON found.";
return;
}
$home_decoded = json_decode($matches[1]);
这与我的API实际输出(没有正确的URL)相反:
file_get_contents("http://strategy-bets.com/archive/archive.php?baseurl=http://www.totalcorner.com");
即使API本身返回的是与JSON混合在一起的HTML。
编辑 :由于您提供了一个有效的URL,我做了更多的调试:
php > print_r(array_map('dechex', array_map('ord', str_split($homeJSON))));
Array
(
[0] => ef
[1] => bb
[2] => bf
[3] => 7b
[4] => 22
[5] => 74
[6] => 6f
[7] => 74
[8] => 61
[9] => 6c
...
字节7b
是开头{
,其中是有效JSON的开始位置。 字节0-3
是UTF-8字节顺序标记 。 因此,尽管我上面的正则表达式解决方案仍然可以使用,但我们也可以清理BOM和任何杂散的空字符,如下所示:
$homeJSON = file_get_contents("http://strategy-bets.com/archive/archive.php?baseurl=http://www.totalcorner.com".$Home_Team_Link);
$homeJSON = trim($homeJSON, "\x0\xEF\xBB\xBF");
$home_decoded = json_decode($homeJSON);
这给了我:
php > var_dump(json_decode($jsonCopy));
object(stdClass)#1 (3) {
["total_goals"]=>
int(26)
["total_games"]=>
int(17)
["average_goals"]=>
string(4) "1.53"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.