json_decode - 返回NULL

时间:2016-03-27 19:42:30

标签: php json byte-order-mark

以下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

1 个答案:

答案 0 :(得分:5)

首先,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究竟是什么,但是,让我们#39;尝试不同的方法,并尝试从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。

编辑:由于您提供了有效的网址,我做了一些调试:

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-3UTF-8 Byte Order Mark。因此,虽然我的上述正则表达式解决方案仍然有效,但我们也可以清理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"
}