[英]Parsing RSS with PHP
我正在嘗試解析RSS: http : //www.mlssoccer.com/rss/en.xml 。
$feed = new DOMDocument();
$feed->load($url)
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
foreach($items as $key => $item)
{
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
$description = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
// do some stuff
}
問題是:我得到“ $ title”和“ $ pubDate”沒有問題,但是由於某種原因,“ $ description”始終為空,其中沒有任何內容。 發生這種行為的原因可能是什么?如何解決?
問題在於CDATA,您需要使用textContent而不是nodeValue來檢索之間的值
<?php
$feed = new DOMDocument();
$feed->load('http://www.mlssoccer.com/rss/en.xml');
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
foreach($items as $key => $item)
{
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
$description = $item->getElementsByTagName('description')->item(0)->textContent; // textContent
}
開頭<description>
標記和開頭<![CDATA[
之間可以有空格。 這是一個文本節點。
因此,如果訪問description
的firstChild,則可能會獲取該空白文本節點。
您可以通過一種通用方式將DOMdocument設置為忽略空白節點:
$feed = new DOMDocument();
$feed->preserveWhiteSpace = FALSE;
$feed->load($url);
另外,您應該簽出XPath,它使讀取DOM更容易:
$xpath = new DOMXpath($feed);
foreach ($xpath->evaluate('//channel/item') as $item) {
$title = $xpath->evaluate('string(title)', $item);
$pubDate = $xpath->evaluate('string(pubDate)', $item);
$description = $xpath->evaluate('string(description)', $item);
// do some stuff
var_dump([$title, $pubData, $description]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.