json_decode在php中返回null [英] json_decode is returning null in php

查看:114
本文介绍了json_decode在php中返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用php中的json_decode解析json. 网址失败,任何人都可以告诉我为什么它失败,并且在php中有json_decode的替代方法吗?

I am trying to parse json using json_decode in php. It is failing for a url, Can any one tell me why its failing and is there ant alternative to json_decode in php ?

这是我的代码

$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在这里为空

//json is null here

推荐答案

file_get_html PHP简单HTML DOM解析器 Not default PHP function应该是

 $html = file_get_contents($url);     

请注意,返回的JSON格式错误,可能是UTF-8字符格式错误,可能编码错误

Please also Note that the returned JSON has an error of Malformed UTF-8 characters, possibly incorrectly encoded

解决此问题

$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

查看实时演示

这篇关于json_decode在php中返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆