解析RSS类

jerry thinkphp 2015年11月18日 收藏
简单但功能强大的PHP解析RSS文件类。
by Vojtech Semecky, webmaster @ webdot . cz最新版本,更新类容,手册,示例参见: http://lastrss.webdot.cz/ http://sssui.com
我只是摘抄过来,由于英文不好,所以稍加汉化了注释
  1. /*
  2.  ======================================================================
  3.  lastRSS 0.9.1
  4.  
  5. 简单但功能强大的PHP解析RSS文件类。
  6. by Vojtech Semecky, webmaster @ webdot . cz
  7.  
  8. 最新版本,更新类容,手册,示例参见:
  9.      http://lastrss.webdot.cz/
  10.     http://sssui.com

  11.  ----------------------------------------------------------------------
  12.  LICENSE

  13.  This program is free software; you can redistribute it and/or
  14.  modify it under the terms of the GNU General Public License (GPL)
  15.  as published by the Free Software Foundation; either version 2
  16.  of the License, or (at your option) any later version.

  17.  This program is distributed in the hope that it will be useful,
  18.  but WITHOUT ANY WARRANTY; without even the implied warranty of
  19.  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20.  GNU General Public License for more details.

  21.  To read the license please visit http://www.gnu.org/copyleft/gpl.html
  22.  ======================================================================
  23. */
  24. /*
  25.     $rss=new lastRSS();             //实例化
  26.     $rss->cache_dir = 'cache';      //设置缓存目录,要手动建立
  27.     $rss->cache_time = 3600;        //设置缓存时间。默认为0,即随访问更新缓存;建议设置为3600,一个小时
  28.     $rss->default_cp = 'UTF-8';     //设置RSS字符编码,默认为UTF-8
  29.     $rss->cp = 'GBK';               //设置输出字符编码,默认为GBK
  30.     $rss->items_limit = 10;         //设置输出数量,默认为10
  31.     $rss->date_format = 'U';        //设置时间格式。默认为字符串;U为时间戳,可以用date设置格式
  32.     $rss->stripHTML = true;         //设置过滤html脚本。默认为false,即不过滤
  33.     $rss->CDATA = 'content';        //设置处理CDATA信息。默认为nochange。另有strip和content两个选项

  34.     $url = 'http://hi.baidu.com/gincn/rss ';
  35.     $data = $rss->Get($url);        //处理RSS并获取内容
  36.     print_r($data);
  37. */
  38. /**
  39. * lastRSS
  40. * 简单但功能强大的PHP解析RSS文件类。
  41. */
  42. class lastRSS {
  43.     // -------------------------------------------------------------------
  44.     // 共有属性
  45.     // -------------------------------------------------------------------
  46.     var $default_cp = 'UTF-8';
  47.     var $CDATA = 'nochange';
  48.     var $cp = '';
  49.     var $items_limit = 0;
  50.     var $stripHTML = False;
  51.     var $date_format = '';

  52.     // -------------------------------------------------------------------
  53.     // 私有属性
  54.     // -------------------------------------------------------------------
  55.     var $channeltags = array ('title', 'link', 'description', 'language', 'copyright', 'managingEditor', 'webMaster', 'lastBuildDate', 'rating', 'docs');
  56.     var $itemtags = array('title', 'link', 'description', 'author', 'category', 'comments', 'enclosure', 'guid', 'pubDate', 'source');
  57.     var $imagetags = array('title', 'url', 'link', 'width', 'height');
  58.     var $textinputtags = array('title', 'description', 'name', 'link');

  59.     // -------------------------------------------------------------------
  60.     // 解析RSS文件,并返回关联数组。
  61.     // -------------------------------------------------------------------
  62.     function Get ($rss_url) {
  63.         //如果启用缓存
  64.         if ($this->cache_dir != '') {
  65.             $cache_file = $this->cache_dir . '/rsscache_' . md5($rss_url);
  66.             $timedif = @(time() - filemtime($cache_file));
  67.             if ($timedif < $this->cache_time) {
  68.                 // 缓存文件是最新,则返回缓存数组
  69.                 $result = unserialize(join('', file($cache_file)));
  70.                 // 如果缓存不为空,则设置$cached=1
  71.                 if ($result) $result['cached'] = 1;
  72.             } else {
  73.                 // 缓存文件已过期,则创建新的缓存文件
  74.                 $result = $this->Parse($rss_url);
  75.                 $serialized = serialize($result);
  76.                 if ($f = @fopen($cache_file, 'w')) {
  77.                     fwrite ($f, $serialized, strlen($serialized));
  78.                     fclose($f);
  79.                 }
  80.                 if ($result) $result['cached'] = 0;
  81.             }
  82.         }
  83.         // 如果未启用缓存,则直接加载文件
  84.         else {
  85.             $result = $this->Parse($rss_url);
  86.             if ($result) $result['cached'] = 0;
  87.         }
  88.         return $result;
  89.     }
  90.     
  91.     // -------------------------------------------------------------------
  92.     // 重定义preg_match(); 返回修正过后的第一个匹配
  93.     // from 'classic' preg_match() array output
  94.     // -------------------------------------------------------------------
  95.     function my_preg_match ($pattern, $subject) {
  96.         // 开始正在匹配
  97.         preg_match($pattern, $subject, $out);

  98.         // 如果结果不为空,则继续
  99.         if(isset($out[1])) {
  100.             // 处理 CDATA (如果存在)
  101.             if ($this->CDATA == 'content') { // 获取 CDATA内容 (不存在 CDATA 标签)
  102.                 $out[1] = strtr($out[1], array('<![CDATA['=>'', ']]>'=>''));
  103.             } elseif ($this->CDATA == 'strip') { // 去除 CDATA
  104.                 $out[1] = strtr($out[1], array('<![CDATA['=>'', ']]>'=>''));
  105.             }

  106.             //转换成设置的编码
  107.             if ($this->cp != '')
  108.                 $out[1] = iconv($this->rsscp, $this->cp.'//TRANSLIT', $out[1]);
  109.             return trim($out[1]);
  110.         } else {
  111.             return '';
  112.         }
  113.     }

  114.     // -------------------------------------------------------------------
  115.     // 替换html实体为真实字符
  116.     // -------------------------------------------------------------------
  117.     function unhtmlentities ($string) {
  118.         // Get HTML entities table
  119.         $trans_tbl = get_html_translation_table (HTML_ENTITIES, ENT_QUOTES);
  120.         // Flip keys<==>values
  121.         $trans_tbl = array_flip ($trans_tbl);
  122.         // Add support for ' entity (missing in HTML_ENTITIES)
  123.         $trans_tbl += array(''' => "'");
  124.         // Replace entities by values
  125.         return strtr ($string, $trans_tbl);
  126.     }

  127.     // -------------------------------------------------------------------
  128.     // Parse() 是由GET()调用的私有方法,用来解析RSS文件.
  129.     // 所以不要在你的代码中使用Parse(),而是用 Get($rss_file)方法来替代.
  130.     // -------------------------------------------------------------------
  131.     function Parse ($rss_url) {
  132.         //打开RSS文件
  133.         if ($f = @fopen($rss_url, 'r')) {
  134.             $rss_content = '';
  135.             while (!feof($f)) {
  136.                 $rss_content .= fgets($f, 4096);
  137.             }
  138.             fclose($f);

  139.             // 解析文件编码 
  140.             $result['encoding'] = $this->my_preg_match("'encoding=[\'\"](.*?)[\'\"]'si", $rss_content);
  141.             //如果文件编码一致则直接使用
  142.             if ($result['encoding'] != '')
  143.                 { $this->rsscp = $result['encoding']; } // This is used in my_preg_match()
  144.             //否则使用默认的编码
  145.             else
  146.                 { $this->rsscp = $this->default_cp; } // This is used in my_preg_match()

  147.             // 解析 CHANNEL信息
  148.             preg_match("'<channel.*?>(.*?)</channel>'si", $rss_content, $out_channel);
  149.             foreach($this->channeltags as $channeltag)
  150.             {
  151.                 $temp = $this->my_preg_match("'<$channeltag.*?>(.*?)</$channeltag>'si", $out_channel[1]);
  152.                 if ($temp != '') $result[$channeltag] = $temp; // Set only if not empty
  153.             }
  154.             // If date_format is specified and lastBuildDate is valid
  155.             if ($this->date_format != '' && ($timestamp = strtotime($result['lastBuildDate'])) !==-1) {
  156.                         // 解析 lastBuildDate 到指定的时间格式
  157.                         $result['lastBuildDate'] = date($this->date_format, $timestamp);
  158.             }

  159.             // 解析 TEXTINPUT
  160.             preg_match("'<textinput(|[^>]*[^/])>(.*?)</textinput>'si", $rss_content, $out_textinfo);
  161.                 // This a little strange regexp means:
  162.                 // Look for tag <textinput> with or without any attributes, but skip truncated version <textinput /> (it's not beggining tag)
  163.             if (isset($out_textinfo[2])) {
  164.                 foreach($this->textinputtags as $textinputtag) {
  165.                     $temp = $this->my_preg_match("'<$textinputtag.*?>(.*?)</$textinputtag>'si", $out_textinfo[2]);
  166.                     if ($temp != '') $result['textinput_'.$textinputtag] = $temp; // Set only if not empty
  167.                 }
  168.             }
  169.             // 解析 IMAGE
  170.             preg_match("'<image.*?>(.*?)</image>'si", $rss_content, $out_imageinfo);
  171.             if (isset($out_imageinfo[1])) {
  172.                 foreach($this->imagetags as $imagetag) {
  173.                     $temp = $this->my_preg_match("'<$imagetag.*?>(.*?)</$imagetag>'si", $out_imageinfo[1]);
  174.                     if ($temp != '') $result['image_'.$imagetag] = $temp; // Set only if not empty
  175.                 }
  176.             }
  177.             // 解析 ITEMS
  178.             preg_match_all("'<item(| .*?)>(.*?)</item>'si", $rss_content, $items);
  179.             $rss_items = $items[2];
  180.             $i = 0;
  181.             $result['items'] = array(); // create array even if there are no items
  182.             foreach($rss_items as $rss_item) {
  183.                 // If number of items is lower then limit: Parse one item
  184.                 if ($i < $this->items_limit || $this->items_limit == 0) {
  185.                     foreach($this->itemtags as $itemtag) {
  186.                         $temp = $this->my_preg_match("'<$itemtag.*?>(.*?)</$itemtag>'si", $rss_item);
  187.                         if ($temp != '') $result['items'][$i][$itemtag] = $temp; // Set only if not empty
  188.                     }
  189.                     // Strip HTML tags and other bullshit from DESCRIPTION
  190.                     if ($this->stripHTML && $result['items'][$i]['description'])
  191.                         $result['items'][$i]['description'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['description'])));
  192.                     // Strip HTML tags and other bullshit from TITLE
  193.                     if ($this->stripHTML && $result['items'][$i]['title'])
  194.                         $result['items'][$i]['title'] = strip_tags($this->unhtmlentities(strip_tags($result['items'][$i]['title'])));
  195.                     // If date_format is specified and pubDate is valid
  196.                     if ($this->date_format != '' && ($timestamp = strtotime($result['items'][$i]['pubDate'])) !==-1) {
  197.                         // convert pubDate to specified date format
  198.                         $result['items'][$i]['pubDate'] = date($this->date_format, $timestamp);
  199.                     }
  200.                     // Item 计数
  201.                     $i++;
  202.                 }
  203.             }

  204.             $result['items_count'] = $i;
  205.             return $result;
  206.         }
  207.         else // 文件打开错误返回False
  208.         {
  209.             return False;
  210.         }
  211.     }
  212. }