【问题标题】:json_decode is returning null in php [closed]json_decode 在 php 中返回 null [关闭]
【发布时间】:2012-10-04 18:54:58
【问题描述】:

我正在尝试在 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为空

【问题讨论】:

    标签: php json


    【解决方案1】:

    file_get_htmlPHP Simple HTML DOM ParserNot 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
    

    See Live Demo

    【讨论】:

    • 感谢您的回答,但实际上使用 file_get_contents 会得到相同的结果。
    • 是的,因为你有 - Malformed UTF-8 characters, possibly incorrectly encoded .. 我会在 @Ishtiaq Ahmed 周围工作
    • 感谢您的帮助。
    • @Ishtiaq Ahmed .. 添加了修复
    • 成功了,非常感谢...... :)
    猜你喜欢
    • 2018-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-13
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多