1

我正在尝试在 php 中使用 json_decode 解析 json。一个 url 失败了,谁能告诉我为什么它失败了,在 php 中是否有 json_decode 的替代方法?

这是我的代码

$url='https://espn.go.com/travel/sports/calendar/getList.json?&xhr=1&date=20121027&type=list&query=null&myTeams=';
$html = file_get_html($url);     
$json=json_decode($html,true);

//json在这里为空

4

1 回答 1

5

file_get_htmlPHP Simple HTML DOM Parser Not default PHP function 应该是

 $html = file_get_contents($url);     

另请注意,返回的 JSON 存在格式错误的 UTF-8 字符错误,可能编码不正确

解决这个问题

$url = 'http://espn.go.com/travel/sports/calendar/getList.json?&xhr=1&date=20121027&type=list&query=null&myTeams=';
$html = file_get_contents($url);
$json = preg_replace('/,\s*([\]}])/m', '$1', utf8_encode($html));
$json = json_decode($json);
echo "<pre>";
print_r($json);

输出

tdClass Object
(
    [nfb] => Array
        (
            [0] => stdClass Object
                (
                    [events] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [id] => 265911
                                    [time] => 12:00 AM ET
                                    [sportId] => 23
                                    [link] => http://espn.go.com/ncf/team/_/name/
                                    [prevLink] => http://espn.go.com/ncf/preview?gameId=323010002
                                    [recapLink] => http://espn.go.com/ncf/recap?gameId=323010002
                                    [shortSport] => ncaa
                                    [homeId] => 2
                                    [awayId] => 245
                                    [homeScore] => -1

        ... So Many More

观看现场演示

于 2012-10-14T17:43:22.820 回答