正在加载……
用php5的simplexml解析各种feed
| |
Posted in LAMP on April 14, 2008 / 引用(0)

用simplexml处理atom数据

很多博客使用atom来输出数据,但是atom使用了名称空间(namespace),所以现在请求被命名的元素和本地名称时必须指定名称空间统一资源标识符(URI),还有一点就是simplexml的xpath方法无法直接query这个xml tree。

PHP 5.1 版开始,SimpleXML 可以直接对带名称空间的文档使用 XPath 查询。和通常一样,XPath 位置路径必须使用名称空间前缀,即使搜索的文档使用默认名称空间也仍然如此。registerXPathNamespace() 函数把前缀和后续查询中使用的名称空间 URL 联系在一起。

下面是使用xpath查询atom文档title元素的例子:

PLAIN TEXT
CODE:
  1. $atom =  simplexml_load_file('http://www.ooso.net/index.php/feed/atom');
  2. $atom->registerXPathNamespace('atom', 'http://www.w3.org/2005/Atom');
  3. $titles = $atom->xpath('//atom:title');
  4. foreach ($titles as $title)
  5.   echo "<h2>" . $title . "</h2>";

用simplexml处理rss数据

wordpress可以输出rss2的数据源,这里面也有一些不同的namespace,比如dc。一个使用simplexml解析rss2的例子:

PLAIN TEXT
PHP:
  1. $ns = array (
  2.         'content' => 'http://purl.org/rss/1.0/modules/content/',
  3.         'wfw' => 'http://wellformedweb.org/CommentAPI/',
  4.         'dc' => 'http://purl.org/dc/elements/1.1/'
  5. );
  6. $articles = array();
  7. // step 1: 获得feed
  8. $blogUrl = 'http://www.ooso.net/index.php/feed/rss2';
  9. $xml = simplexml_load_url($blogUrl);
  10. // step 2: 获得channel metadata
  11. $channel = array();
  12. $channel['title']       = $xml->channel->title;
  13. $channel['link']        = $xml->channel->link;
  14. $channel['description'] = $xml->channel->description;
  15. $channel['pubDate']     = $xml->pubDate;
  16. $channel['timestamp']   = strtotime($xml->pubDate);
  17. $channel['generator']   = $xml->generator;
  18. $channel['language']    = $xml->language;
  19. // step 3: 获得articles
  20. foreach ($xml->channel->item as $item) {
  21.         $article = array();
  22.         $article['channel'] = $blog;
  23.         $article['title'] = $item->title;
  24.         $article['link'] = $item->link;
  25.         $article['comments'] = $item->comments;
  26.         $article['pubDate'] = $item->pubDate;
  27.         $article['timestamp'] = strtotime($item->pubDate);
  28.         $article['description'] = (string) trim($item->description);
  29.         $article['isPermaLink'] = $item->guid['isPermaLink'];
  30.         // get data held in namespaces
  31.         $content = $item->children($ns['content']);
  32.         $dc      = $item->children($ns['dc']);
  33.         $wfw     = $item->children($ns['wfw']);
  34.         $article['creator'] = (string) $dc->creator;
  35.         foreach ($dc->subject as $subject)
  36.                 $article['subject'][] = (string)$subject;
  37.         $article['content'] = (string)trim($content->encoded);
  38.         $article['commentRss'] = $wfw->commentRss;
  39.         // add this article to the list
  40.         $articles[$article['timestamp']] = $article;
  41. }

这个例子中,使用children方法来获得名称空间中的数据:

PLAIN TEXT
PHP:
  1. $dc      = $item->children($ns['dc']);
This entry comes from 本站原创 and has been read for 291 times.It is tagged with , , , .
发表评论

昵称

网址

电邮

OpenID登入 高级选项 表情