Home  >  Article  >  php教程  >  用PHP读取RSS feed的代码

用PHP读取RSS feed的代码

WBOY
WBOYOriginal
2016-06-13 12:27:301144browse

而助易网的rss读取就是在这个程序的基础上稍做改造而成,主
要是输出了一个数组字符串以及解决编码问题。

php源代码及代码详细解释如下:

//RSS源地址列表数组
$rssfeed = array("http://www.jb51.net/feed",
"http://rss.sina.com.cn/news/allnews/sports.xml",
"http://ent.163.com/special/00031K7Q/rss_toutiao.xml",
"http://tech.163.com/special/00091JPQ/techimportant.xml");

//设置编码为UTF-8
header('Content-Type:text/html;charset= UTF-8');     

for($i=0;$i    $buff = "";
    $rss_str="";
    //打开rss地址,并读取,读取失败则中止
    $fp = fopen($rssfeed[$i],"r") or die("can not open $rssfeed"); 
    while ( !feof($fp) ) {
        $buff .= fgets($fp,4096);
    }
    //关闭文件打开
    fclose($fp);

    //建立一个 XML 解析器
    $parser = xml_parser_create();
    //xml_parser_set_option -- 为指定 XML 解析进行选项设置
    xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
    //xml_parse_into_struct -- 将 XML 数据解析到数组$values中
    xml_parse_into_struct($parser,$buff,$values,$idx);
    //xml_parser_free -- 释放指定的 XML 解析器
    xml_parser_free($parser);

    foreach ($values as $val) {
        $tag = $val["tag"];
        $type = $val["type"];
        $value = $val["value"];
        //标签统一转为小写
        $tag = strtolower($tag);

        if ($tag == "item" && $type == "open"){
            $is_item = 1;
        }else if ($tag == "item" && $type == "close") {
            //构造输出字符串
            $rss_str .= "".$title."
";
            $is_item = 0;
        }
        //仅读取item标签中的内容
        if($is_item==1){
            if ($tag == "title") {$title = $value;}        
            if ($tag == "link") {$link = $value;}
        }
    }
    //输出结果
    echo $rss_str."
";
}
?>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn