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

 时间:2026-02-13 11:58:36

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、直接上调试通过的代码

<?php

function 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更新系统
  • 什么情况下不能喝红茶
  • 石榴视频应用开启兑换服务怎么做
  • 辊型设计的主要步骤有那些?
  • 热门搜索
    西安旅游景点图片 赵县旅游 乌镇旅游攻略一日游 长崎旅游 上海旅游酒店 威海旅游网 云南大学旅游文化 国庆去哪里旅游好 上海到台湾旅游 长白山旅游地图