PHP利用RSS订阅别处文章

来源:互联网 发布:海外房产 知乎 编辑:程序博客网 时间:2024/05/18 03:08

这篇文章是接上篇利用PHP操作XML文件的。RSS是基于XML的一种形式,它的具体规范如下(我们以截取的新浪RSS订阅频道的格式来看):

输入:http://rss.sina.com.cn/news/world/focus15.xml   查看页面源码就可以看到RSS的结构:

<?xml version="1.0" encoding="utf-8"?><?xml-stylesheet type="text/xsl" title="XSL Formatting" href="/show_new_final.xsl" media="all"?><rss version="2.0"><channel><title><![CDATA[国际要闻-新浪新闻]]></title><image><title><![CDATA[新闻中心-国际新闻]]></title><link>http://news.sina.com.cn/world</link><url>http://www.sinaimg.cn/home/deco/2009/0330/logo_home_news.gif</url></image><description><![CDATA[国际新闻-焦点新闻]]></description><link>http://news.sina.com.cn/491/2008/0827/1.html</link><language>zh-cn</language><generator>WWW.SINA.COM.CN</generator><ttl>5</ttl><copyright><![CDATA[Copyright 1996 - 2012 SINA Inc. All Rights Reserved]]></copyright><pubDate>Sat, 22 Dec 2012 05:32:05 GMT</pubDate><category><![CDATA[]]></category><item><title><![CDATA[111个国家支持暂缓使用死刑 中美朝等41国反对]]></title><link>http://go.rss.sina.com.cn/redirect.php?url=http://news.sina.com.cn/w/2012-12-22/120825871683.shtml</link><author>WWW.SINA.COM.CN</author><guid>http://go.rss.sina.com.cn/redirect.php?url=http://news.sina.com.cn/w/2012-12-22/120825871683.shtml</guid><category><![CDATA[国际新闻-焦点新闻]]></category><pubDate>Sat, 22 Dec 2012 04:08:09 GMT</pubDate><comments></comments><description><![CDATA[  【法新社联合国12月20日电】周四,在联大讨论人权问题的主旨会议上,有创纪录的111个国家投票支持暂缓使用死刑。  虽然这次投票在法律上不具备约束力,但是人权活动分子说,每两年举行一次的表决,是向那些依然保留死刑的国家发出的强烈信号,这些数量在逐步减少的国家....]]></description></item>  </channel></rss>

具体规范信息是代表什么意思,根据标签的内容我们就可以很容易的知道,下面我们写一个rss.php来读取这个xml,从而获取这上面的文章:

<?php header("Content-Type:text/html;charset=utf-8"); ?><html>     <head>      <title>XML</title>     </head> <body><?php     $dom = simplexml_load_file("http://rss.sina.com.cn/news/world/focus15.xml"); //var_dump($dom);?> <h2>The example of RSS</h2> <ul> <?php       foreach($dom->channel->item as $item)   {         print("<li>");   print("<a href='$item->link'>");   print($item->title);   print("</a>");   print("</li>");   }?> </ul>     </body></html>

注意这个函数:simplexml_load_file() ; 它既可以读本地的xml文件,也可以读网络上的xml。

运行结果:

                                                     

Ok, That's  all ....    天道酬勤!!

 

原创粉丝点击