因为网站需要读取不同来源的rss feed,写了一个php程序来循环读取rss feed,为了方便阅读及了解程序实现过程,加上了注释,和大家共同学习。而助易网的rss读取就是在这个程序的基础上稍做改造而成,主要是输出了一个数组字符串以及解决编码问题。
php源代码及代码详细解释如下:
- <?php
-
- $rssfeed = array("http://www.jzxue.com/rss/12.xml",
- "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");
-
-
- header('Content-Type:text/html;charset= UTF-8');
-
- for($i=0;$i<sizeof($rssfeed);$i++){
- $buff = "";
- $rss_str="";
-
- $fp = fopen($rssfeed[$i],"r") or die("can not open $rssfeed");
- while ( !feof($fp) ) {
- $buff .= fgets($fp,4096);
- }
-
- fclose($fp);
-
-
- $parser = xml_parser_create();
-
- xml_parser_set_option($parser,XML_OPTION_SKIP_WHITE,1);
-
- xml_parse_into_struct($parser,$buff,$values,$idx);
-
- 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 .= "<a href='".$link."' target=_blank>".$title."</a><br />";
- $is_item = 0;
- }
-
- if($is_item==1){
- if ($tag == "title") {$title = $value;}
- if ($tag == "link") {$link = $value;}
- }
- }
-
- echo $rss_str."<br />";
- }
- ?>
(责任编辑:admin) |