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

 时间:2024-10-14 00:31:19

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(刻八圄俏9;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());

  • 哔哩哔哩怎么开启收藏同时追番/追剧?
  • 红米K20Pro人脸解锁在哪?RedmiK20Pro更新系统
  • 什么情况下不能喝红茶
  • 石榴视频应用开启兑换服务怎么做
  • 辊型设计的主要步骤有那些?
  • 热门搜索
    腱鞘炎怎么治疗 宝宝咳嗽有痰怎么办 电脑死机怎么办 teacher怎么读 银耳怎么煮才会粘稠 桫椤怎么读 怎么炒股 电脑自动锁屏怎么设置 怎么找回微信密码 头晕耳鸣是怎么回事