PHP读取XML数据的RSS(Feed)的简单实例代码
分类:PHP_Python| 发布:佚名| 查看:310 | 发表时间:2014/8/18
最近在弄博客,但各种博客间同步比较麻烦,好在每一个博客都有自己的RSS聚合系统,可以通过RSS实现博客同步调用,于是自己动手用RSS实现博客同步发布,在其中就研究一下PHP读RSS。
RSS是用XML来书写的,XML 是一种数据存储格式。PHP读取XML数据有三种方法:用XML解析函数、DOM模块和正则表达式,最直接地就是直接解析XML,获取XML中的数据。
以下是解析代码:
代码如下:
02 | error_reporting (E_ALL^E_NOTICE); |
03 | $rssfeed = "feed.xml" ; |
04 | header( 'Content-Type:text/html;charset= UTF-8' ); |
07 | $fp = fopen ( $rssfeed , "r" ) or die ( "can not open $rssfeed" ); |
08 | while ( ! feof ( $fp ) ) { |
09 | $buff .= fgets ( $fp ,4096); |
14 | $parser = xml_parser_create(); |
16 | xml_parser_set_option( $parser ,XML_OPTION_SKIP_WHITE,1); |
18 | xml_parse_into_struct( $parser , $buff , $values , $idx ); |
20 | xml_parser_free( $parser ); |
21 | foreach ( $values as $val ) { |
24 | $value = $val [ "value" ]; |
26 | $tag = strtolower ( $tag ); |
27 | if ( $tag == "item" && $type == "open" ){ |
29 | } else if ( $tag == "item" && $type == "close" ) { |
31 | echo "<a href=" ".$link." " target=" _blank ">" . $title ."</a> |
39 | if ( $tag == "title" ) { $title = $value ;} |
40 | if ( $tag == "link" ) { $link = $value ;} |
41 | if ( $tag == "content:encoded" ){ $content = $value ;} |
以下是用该程序读取feed的效果:
