2009-09-21 86 views
1

我試圖使用PHP在列表中打印RSS 2.0 feed中的所有<title><description>元素。我可以簡單地使用這些元素:$rss->xpath('rss/channel/item/title | rss/channel/item/description')但我想使用它有點不同。

我想用PHP使用foreach語句像這樣通過所有<item>元素進行迭代:

<?php 
foreach($xml->xpath('/rss/channel/item') as $item){ 
    print_r($item->xpath('title')); 
} 
?> 

$item->xpath('title')不會返回title元素中的文本,但它返回一個數組:

Array 
(
    [0] => SimpleXMLElement Object 
    (
     [0] => Ubuntu 10.04 LTS 'Lucid Lynx' laat Gnome 3 nog links liggen 
    ) 
) 

爲什麼它返回一個數組而不是元素內的文本?

回答

1

嘗試:

foreach($xml->xpath('/rss/channel/item') as $item) 
{ 
    print_r($item->title); // This pulls out the simpleXML object 
    print_r((string)$item->title); // This pulls out the string as expected 
} 

沒有必要使用SimpleXML時使用另一個XPath查詢,所述第一的XPath將拔出的SimpleXML對象匹配XPath的陣列。然後,您需要做的就是訪問節點,就好像它是SimpleXML對象的屬性一樣。如果您希望將它用作字符串,則需要將屬性前面的(string)放在一個字符串中。

-1

嘗試'rss/channel/item。' (帶點)

+0

Hi Powtac, 該點沒有返回結果...無論如何它在哪裏? ^^ – Harmen 2009-09-21 15:23:21

0

xpath函數返回與路徑匹配的元素數組。所以這就是爲什麼你用一個元素獲得外部數組。你不想用xpath來獲得標題。你想從元素中獲得title屬性。只需直接訪問它。

0

嘗試:

$item->xpath('string(title)')