PHP 使用 SimpleXML 来解析 XML 很方便,解析 RSS 也是轻松愉快,不过要解析 WordPress 的 RSS 时,遇到 XML Tag 的名称有「:」,造成解析不到,要怎么解决呢?
PHP 使用 SimpleXML 遇到冒号「:」的解法
WordPress RSS 在内容的部分,有此标签:,而这个标签在 SimpleXML 解析是无法直接取用的。
下述有几种方式可以抓到:
方法1
下述的 http://purl.org/rss/1.0/modules/content/,取自 XML 最上面的定义,如下范例:
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
$rss = simplexml_load_file('http://feeds.feedburner.com/tsungblog');
foreach ($rss->channel->item as $i => $item) {
// echo $item->children('http://purl.org/dc/elements/1.1/')->encoded;
$ns_content = $item->children('http://purl.org/rss/1.0/modules/content/');
echo $ns_content->encoded;
}
?>
方法2
使用 PHP SimpleXMLElemenX children 的参数
public SimpleXMLElement SimpleXMLElement::children ([ string $ns [, bool $is_prefix = false ]] )
注:ns = namespace
$rss = simplexml_load_file('http://feeds.feedburner.com/tsungblog');
foreach ($rss->channel->item as $i => $item) {
$ns_content = $item->children('content', true);
echo $ns_content->encoded;
}
?>