2011-08-05 13 views
2

不同屬性的價值,我有一些XML:目標XML節點,然後返回使用SimpleXML

<release id="2276808" status="Accepted"> 
    <images> 
     <image height="600" type="primary" uri="http://s.dsimg.com/image/R-2276808-1302966902.jpeg" uri150="http://s.dsimg.com/image/R-150-2276808-1302966902.jpeg" width="600"/>      
     <image height="600" type="secondary" uri="http://s.dsimg.com/image/R-2276808-1302966912.jpeg" uri150="http://s.dsimg.com/image/R-150-2276808-1302966912.jpeg" width="600"/> 
     <image height="600" type="secondary" uri="http://s.dsimg.com/image/R-2276808-1302966919.jpeg" uri150="http://s.dsimg.com/image/R-150-2276808-1302966919.jpeg" width="600"/><image height="600" type="secondary" uri="http://s.dsimg.com/image/R-2276808-1302966929.jpeg" uri150="http://s.dsimg.com/image/R-150-2276808-1302966929.jpeg" width="600"/> 
    </images> ... 

我使用SimpleXML和PHP 5.3。

我想定位image節點,其中type="primary"並返回uri屬性的值。

我已經得到最接近的是:

$xml->xpath('/release/images/image[@type="primary"]')->attributes()->uri; 

,因爲你不能xpath後調用attribute()方法,該方法將失敗。

+0

*好*問題,+1。請參閱我的答案以獲得純XPath解決方案 - 一種單行表達式,評估時會生成所需值。還包括一個解釋。 –

回答

0

如何:

$xml = new SimpleXMLElement(file_get_contents('feed.xml')); 
$theUriArray = $xml->xpath('/release/images/image[@type="primary"]'); 
$theUri = $theUriArray[0]->attributes()->uri; 

echo($theUri); 
2

純的XPath 1.0表達式來實現的屬性是:

"/release/images/image[@type="primary"]/@uri" 

可能是你只解決您的XPath。

0

雖然我的內置DOM文檔,而不是的SimpleXML和爲此並非所有熟悉的SimpleXML ...

我相信$xml->xpath('/release/images/image[@type="primary"]')應該給你的節點列表的忠實粉絲,不是一個單一的節點。

在你的情況,我會想到一個可能的解決方案是簡單的

$nodes = $xml->xpath('/release/images/image[@type="primary"]'); // get matching nodes 
$node = reset($nodes); // get first item 
$uri = $node->attributes()->uri; 

既然你特別提到使用SimpleXML,我建議你嘗試尋找你打電話的結果$xml->path(...) 但對於完整性,這是我如何使用DOM文檔和DOMXPath做(這將正常工作,保證,測試和所有):

$doc = new DOMDocument('1.0', 'utf8'); 
$doc->loadXML($yourXMLString); 

$xpath = new DOMXPath($doc); 
$nodes = $xpath->query('/release/images/image[@type="primary"]'); 

$theNodeYouWant = $nodes->item(0); // the first node matching the query 
$uri = $theNodeYouWant->getAttribute('uri'); 

這似乎更詳細一點,但是這主要是因爲我包含在初始化爲這一個。

2

我想指定的圖像節點,在type="primary「,爲uri屬性返回 值

使用此XPath的一個班輪表達

/*/images/image[@type="primary"]/@uri 

這選擇image元素的名稱爲uri的屬性,該元素的字符串值爲type屬性是"primary",這是一個images元素的子元素,它是XML文檔中頂層元素的子元素。

獲取屬性的只是值,使用此XPath表達式

string(/*/images/image[@type="primary"]/@uri) 

請注意:這是一個純粹的XPath的解決方案,可與任何W3C的XPath使用 - 兼容的引擎。