2009-07-27 93 views
14

我試圖從Flickr讀取RSS源,但它有一些節點無法通過簡單XML(media:thumbnail,flickr:profile等)讀取。簡單XML - 處理節點中的冒號

我該如何解決這個問題?當我查看DOM的文檔時,我的頭很痛。所以我想避免它,因爲我不想學習。

我試圖通過這種方式得到縮略圖。

+0

相關:[用於在標記名稱中用冒號解析XML的PHP​​庫](http://stackoverflow.com/q/1575788/367456) – hakre 2013-10-24 16:08:51

回答

18

該解決方案在this nice article中進行了說明。您需要使用children()方法來訪問包含名稱空間的XML元素。此代碼段摘自文章:

$feed = simplexml_load_file('http://www.sitepoint.com/recent.rdf'); 
foreach ($feed->item as $item) { 
    $ns_dc = $item->children('http://purl.org/dc/elements/1.1/'); 
    echo $ns_dc->date; 
}
+0

如果XML具有此標記那麼你會得到鏈接? – 2015-08-26 21:20:11

2

你在處理命名空間嗎?我認爲你需要使用 - > children方法。

$ns_dc = $item->children('http://namespace.org/'); 

你能提供一個帶有xml聲明的代碼片段嗎?

1

使用最新版本,現在可以引用帶大括號的冒號節點。

$item->{'itunes:duration'} 
0

的使用的訪問的命名空間XML節點PHP甚至更簡單的方法,無需聲明命名空間是....

爲了從下面的源

<item> 
    <title>My important article</title> 
    <pubDate>Mon, 29 Feb 2017 00:00:00 +0000</pubDate> 
    <link>https://myxmlsource.com/32984</link> 
    <guid>https://myxmlsource.com/32984</guid> 
    <author>Blogs, Jo</author> 
    <su:departments> 
    <su:department>Human Affairs</su:department> 
    </su:departments> 
    <su:authorHash>4f329b923419b3cb2c654d615e22588c</su:authorHash> 
    <su:authorEmail>hIwW14tLc+4l/oo7agmRrcjwe531u+mO/3IG3xe5jMg=</su:authorEmail> 
    <dc:identifier>/32984/Download/0032984-11042.docx</dc:identifier> 
    <dc:format>Journal article</dc:format> 
    <dc:creator>Blogs, Jo</dc:creator> 
    <slash:comments>0</slash:comments> 
</item> 
得到的 <su:authorEmail值>

使用下面的代碼:

$rss = new DOMDocument(); 

$rss->load('https://myxmlsource.com/rss/xml'); 

$nodes = $rss->getElementsByTagName('item'); 

foreach ($nodes as $node) { 
    $title = $node->getElementsByTagName('title')->item(0)->nodeValue; 
    $author = $node->getElementsByTagName('author')->item(0)->nodeValue; 
    $authorHash = $node->getElementsByTagName('authorHash')->item(0)->nodeValue; 
    $department = $node->getElementsByTagName('department')->item(0)->nodeValue; 
    $email = decryptEmail($node->getElementsByTagName('authorEmail')->item(0)->nodeValue); 
}