新浪滚动新闻JSON解析(PHP版本)

2025-05-06 23:40:25

1、首先我们要知道php5.2以后自带json_decode函数,但是对json文本串的格式要求非常严格。1. json字符串必须以双引号包含2. json字符串必须是utf8编码3.不能有多余的逗号

2、我们通过分析访问新浪滚动新闻产生的http请求找到请求rollnews_ch_out_interface.php文件时候的相应为一json

新浪滚动新闻JSON解析(PHP版本)

3、使用php的file_get_contents()方法访问以上页面获取json内容,直接使用json_decode()方法解析发现结果为null

4、通过分析json_decode()对json格式的三点格式要求1. json字符串必须以双引号包含2. json字符串必须是utf8编码3.不能有多余的逗号我们对json文本进行了处理

5、去掉json开始中的"var jsonData = "和尾部的";"两行代码如下$html=str_replace('var jsonData = ', '', $html);$html=str_replace(';', '', $html);

6、以上处理后我们发现还是失败,自习分析发现新浪滚动新闻的json实在太不符合PHP json_decode()方法的格式要求,所以我们进行了进一步的处理

7、直接上调试通过的代码<?phpfun罕铞泱殳ction getNewsList(){ $url='稆糨孝汶;http://roll.news.sina.com.cn/interface/rollnews_ch_out_interface.php?col=96&spec=&type=&ch=01&k=&offset_page=0&offset_num=0&num=1&asc=&page=1'; $html=file_get_contents($url); $html = trim($html); $html = iconv('gbk', 'utf-8', $html); $html=str_replace('var jsonData = ', '', $html); $html=str_replace(';', '', $html); $html=str_replace("\n", '', $html); $html=str_replace("\t", '', $html); $html=str_replace("'", '"', $html); $html=str_replace(' ', '', $html); $html=str_replace('serverSeconds', '"serverSeconds"', $html); $html=str_replace('last_time', '"last_time"', $html); $html=str_replace('path', '"path"', $html); $html=str_replace('count', '"count"', $html); $html=str_replace('offset_page', '"offset_page"', $html); $html=str_replace('offset_num', '"offset_num"', $html); $html=str_replace('list', '"list"', $html); $html=str_replace('channel', '"channel"', $html); $html=str_replace('title', '"title"', $html); $html=str_replace(',id', ',"id"', $html); $html=str_replace('cType', '"cTyle"', $html); $html=str_replace('url', '"url"', $html); $html=str_replace('pic', '"pic"', $html); $html=str_replace(',time', ',"time"', $html); $html=str_replace('type', '"type"', $html); $html=str_replace('[{"title"', '{"title"', $html); $html=str_replace('}],"count"', '},"count"', $html); return json_decode($html,true);}//print_r(getContentArray($url));var_dump(getNewsList());print_r(json_last_error());

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢