2015-07-10 90 views
1

我有這個xml文件父節點:PHP:獲得其中的孩子= '值'

<friends> 
    <friend> 
     <name>xxx</name> 
     <pays>France</pays> 
    </friend> 
    <friend> 
     <name>yyy</name> 
     <country>France</country> 
    </friend> 
    <friend> 
     <name>zzz</name> 
     <country>USA</country> 
    </friend> 
</friends> 

爲了讓我的數據,我使用這個PHP代碼:

$xml = simplexml_load_file('friends.xml'); 
$friendsXML = $xml->friend; 

,工作正常,但返回所有的朋友。

現在我只想檢索誰是來自法國的朋友:

country = 'france'. 

誰能幫我做嗎?

+0

簡單的XPath://'國家[文本()= '法國']/..' –

+0

或許更好的複製:[PHP基於字段的值的SimpleXML得到的特定項目( http://stackoverflow.com/q/17537909/367456) – hakre

+0

或者更好的重複:[在XPath中實現條件](http://stackoverflow.com/q/3448005/367456) – hakre

回答

1

我會使用XPath來處理這樣的事情。嘗試:

$res = $xml->xpath('friend[country = "france"]'); 
echo $res[0]; 
+0

非常感謝,它是工作正常;);) – zakariag