Rumah  >  Artikel  >  php教程  >  解析RSS类

解析RSS类

WBOY
WBOYasal
2016-06-07 11:44:491288semak imbas

简单但功能强大的PHP解析RSS文件类。
by Vojtech Semecky, webmaster @ webdot . cz最新版本,更新类容,手册,示例参见: http://lastrss.webdot.cz/ http://sssui.com
我只是摘抄过来,由于英文不好,所以稍加汉化了注释/*<br>  ======================================================================<br>  lastRSS 0.9.1<br>  <br> 简单但功能强大的PHP解析RSS文件类。<br> by Vojtech Semecky, webmaster @ webdot . cz<br>  <br> 最新版本,更新类容,手册,示例参见:<br>      http://lastrss.webdot.cz/<br>     http://sssui.com<br> <br>  ----------------------------------------------------------------------<br>  LICENSE<br> <br>  This program is free software; you can redistribute it and/or<br>  modify it under the terms of the GNU General Public License (GPL)<br>  as published by the Free Software Foundation; either version 2<br>  of the License, or (at your option) any later version.<br> <br>  This program is distributed in the hope that it will be useful,<br>  but WITHOUT ANY WARRANTY; without even the implied warranty of<br>  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br>  GNU General Public License for more details.<br> <br>  To read the license please visit http://www.gnu.org/copyleft/gpl.html<br>  ======================================================================<br> */<br> /*<br>     $rss=new lastRSS();             //实例化<br>     $rss->cache_dir = 'cache';      //设置缓存目录,要手动建立<br>     $rss->cache_time = 3600;        //设置缓存时间。默认为0,即随访问更新缓存;建议设置为3600,一个小时<br>     $rss->default_cp = 'UTF-8';     //设置RSS字符编码,默认为UTF-8<br>     $rss->cp = 'GBK';               //设置输出字符编码,默认为GBK<br>     $rss->items_limit = 10;         //设置输出数量,默认为10<br>     $rss->date_format = 'U';        //设置时间格式。默认为字符串;U为时间戳,可以用date设置格式<br>     $rss->stripHTML = true;         //设置过滤html脚本。默认为false,即不过滤<br>     $rss->CDATA = 'content';        //设置处理CDATA信息。默认为nochange。另有strip和content两个选项<br> <br>     $url = 'http://hi.baidu.com/gincn/rss ';<br>     $data = $rss->Get($url);        //处理RSS并获取内容<br>     print_r($data);<br> */<br> /**<br> * lastRSS<br> * 简单但功能强大的PHP解析RSS文件类。<br> */<br> class lastRSS {<br>     // -------------------------------------------------------------------<br>     // 共有属性<br>     // -------------------------------------------------------------------<br>     var $default_cp = 'UTF-8';<br>     var $CDATA = 'nochange';<br>     var $cp = '';<br>     var $items_limit = 0;<br>     var $stripHTML = False;<br>     var $date_format = '';<br> <br>     // -------------------------------------------------------------------<br>     // 私有属性<br>     // -------------------------------------------------------------------<br>     var $channeltags = array ('title', 'link', 'description', 'language', 'copyright', 'managingEditor', 'webMaster', 'lastBuildDate', 'rating', 'docs');<br>     var $itemtags = array('title', 'link', 'description', 'author', 'category', 'comments', 'enclosure', 'guid', 'pubDate', 'source');<br>     var $imagetags = array('title', 'url', 'link', 'width', 'height');<br>     var $textinputtags = array('title', 'description', 'name', 'link');<br> <br>     // -------------------------------------------------------------------<br>     // 解析RSS文件,并返回关联数组。<br>     // -------------------------------------------------------------------<br>     function Get ($rss_url) {<br>         //如果启用缓存<br>         if ($this->cache_dir != '') {<br>             $cache_file = $this->cache_dir . '/rsscache_' . md5($rss_url);<br>             $timedif = @(time() - filemtime($cache_file));<br>             if ($timedif cache_time) {<br>                 // 缓存文件是最新,则返回缓存数组<br>                 $result = unserialize(join('', file($cache_file)));<br>                 // 如果缓存不为空,则设置$cached=1<br>                 if ($result) $result['cached'] = 1;<br>             } else {<br>                 // 缓存文件已过期,则创建新的缓存文件<br>                 $result = $this->Parse($rss_url);<br>                 $serialized = serialize($result);<br>                 if ($f = @fopen($cache_file, 'w')) {<br>                     fwrite ($f, $serialized, strlen($serialized));<br>                     fclose($f);<br>                 }<br>                 if ($result) $result['cached'] = 0;<br>             }<br>         }<br>         // 如果未启用缓存,则直接加载文件<br>         else {<br>             $result = $this->Parse($rss_url);<br>             if ($result) $result['cached'] = 0;<br>         }<br>         return $result;<br>     }<br>     <br>     // -------------------------------------------------------------------<br>     // 重定义preg_match(); 返回修正过后的第一个匹配<br>     // from 'classic' preg_match() array output<br>     // -------------------------------------------------------------------<br>     function my_preg_match ($pattern, $subject) {<br>         // 开始正在匹配<br>         preg_match($pattern, $subject, $out);<br> <br>         // 如果结果不为空,则继续<br>         if(isset($out[1])) {<br>             // 处理 CDATA (如果存在)<br>             if ($this->CDATA == 'content') { // 获取 CDATA内容 (不存在 CDATA 标签)<br>                 $out[1] = strtr($out[1], array(''', ']]>'=>''));<br>             } elseif ($this->CDATA == 'strip') { // 去除 CDATA<br>                 $out[1] = strtr($out[1], array(''', ']]>'=>''));<br>             }<br> <br>             //转换成设置的编码<br>             if ($this->cp != '')<br>                 $out[1] = iconv($this->rsscp, $this->cp.'//TRANSLIT', $out[1]);<br>             return trim($out[1]);<br>         } else {<br>             return '';<br>         }<br>     }<br> <br>     // -------------------------------------------------------------------<br>     // 替换html实体为真实字符<br>     // -------------------------------------------------------------------<br>     function unhtmlentities ($string) {<br>         // Get HTML entities table<br>         $trans_tbl = get_html_translation_table (HTML_ENTITIES, ENT_QUOTES);<br>         // Flip keysvalues<br>         $trans_tbl = array_flip ($trans_tbl);<br>         // Add support for ' entity (missing in HTML_ENTITIES)<br>         $trans_tbl += array(''' => "'");<br>         // Replace entities by values<br>         return strtr ($string, $trans_tbl);<br>     }<br> <br>     // -------------------------------------------------------------------<br>     // Parse() 是由GET()调用的私有方法,用来解析RSS文件.<br>     // 所以不要在你的代码中使用Parse(),而是用 Get($rss_file)方法来替代.<br>     // -------------------------------------------------------------------<br>     function Parse ($rss_url) {<br>         //打开RSS文件<br>         if ($f = @fopen($rss_url, 'r')) {<br>             $rss_content = '';<br>             while (!feof($f)) {<br>                 $rss_content .= fgets($f, 4096);<br>             }<br>             fclose($f);<br> <br>             // 解析文件编码 <br>             $result['encoding'] = $this->my_preg_match("'encoding=[\'\"](.*?)[\'\"]'si", $rss_content);<br>             //如果文件编码一致则直接使用<br>             if ($result['encoding'] != '')<br>                 { $this->rsscp = $result['encoding']; } // This is used in my_preg_match()<br>             //否则使用默认的编码<br>             else<br>                 { $this->rsscp = $this->default_cp; } // This is used in my_preg_match()<br> <br>             // 解析 CHANNEL信息<br>             preg_match("'<channel.>(.*?)'si", $rss_content, $out_channel);<br>             foreach($this->channeltags as $channeltag)<br>             {<br>                 $temp = $this->my_preg_match("'(.*?)$channeltag>'si", $out_channel[1]);<br>                 if ($temp != '') $result[$channeltag] = $temp; // Set only if not empty<br>             }<br>             // If date_format is specified and lastBuildDate is valid<br>             if ($this->date_format != '' && ($timestamp = strtotime($result['lastBuildDate'])) !==-1) {<br>                         // 解析 lastBuildDate 到指定的时间格式<br>                         $result['lastBuildDate'] = date($this->date_format, $timestamp);<br>             }<br> <br>             // 解析 TEXTINPUT<br>             preg_match("'<textinput>]*[^/])>(.*?)</textinput>'si", $rss_content, $out_textinfo);<br>                 // This a little strange regexp means:<br>                 // Look for tag <textinput> with or without any attributes, but skip truncated version <textinput></textinput> (it's not beggining tag)<br>             if (isset($out_textinfo[2])) {<br>                 foreach($this->textinputtags as $textinputtag) {<br>                     $temp = $this->my_preg_match("'(.*?)$textinputtag>'si", $out_textinfo[2]);<br>                     if ($temp != '') $result['textinput_'.$textinputtag] = $temp; // Set only if not empty<br>                 }<br>             }<br>             // 解析 IMAGE<br>             preg_match("'<image.>(.*?)'si", $rss_content, $out_imageinfo);<br>             if (isset($out_imageinfo[1])) {<br>                 foreach($this->imagetags as $imagetag) {<br>                     $temp = $this->my_preg_match("'(.*?)$imagetag>'si", $out_imageinfo[1]);<br>                     if ($temp != '') $result['image_'.$imagetag] = $temp; // Set only if not empty<br>                 }<br>             }<br>             // 解析 ITEMS<br>             preg_match_all("'<item>(.*?)</item>'si", $rss_content, $items);<br>             $rss_items = $items[2];<br>             $i = 0;<br>             $result['items'] = array(); // create array even if there are no items<br>             foreach($rss_items as $rss_item) {<br>                 // If number of items is lower then limit: Parse one item<br>                 if ($i items_limit || $this->items_limit == 0) {<br>                     foreach($this->itemtags as $itemtag) {<br>                         $temp = $this->my_preg_match("'(.*?)$itemtag>'si", $rss_item);<br>                         if ($temp != '') $result['items'][$i][$itemtag] = $temp; // Set only if not empty<br>                     }<br>                     // Strip HTML tags and other bullshit from DESCRIPTION<br>                     if ($this->stripHTML && $result['items'][$i]['description'])<br>                         $result['items'][$i]['description'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['description'])));<br>                     // Strip HTML tags and other bullshit from TITLE<br>                     if ($this->stripHTML && $result['items'][$i]['title'])<br>                         $result['items'][$i]['title'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['title'])));<br>                     // If date_format is specified and pubDate is valid<br>                     if ($this->date_format != '' && ($timestamp = strtotime($result['items'][$i]['pubDate'])) !==-1) {<br>                         // convert pubDate to specified date format<br>                         $result['items'][$i]['pubDate'] = date($this->date_format, $timestamp);<br>                     }<br>                     // Item 计数<br>                     $i++;<br>                 }<br>             }<br> <br>             $result['items_count'] = $i;<br>             return $result;<br>         }<br>         else // 文件打开错误返回False<br>         {<br>             return False;<br>         }<br>     }<br> }</image.></textinput></channel.>

AD:真正免费,域名+虚机+企业邮箱=0元

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn