2012-08-15 54 views
3

我將以下XML文件加載到php simplexml中。simplexml,返回具有相同標記的多個項目

<adf> 
<prospect> 
<customer> 
<name part="first">Bob</name> 
<name part="last">Smith</name> 
</customer> 
</prospect> 
</adf> 

使用

$customers = new SimpleXMLElement($xmlstring); 

這將返回 「鮑勃」,但我怎麼回的姓氏?

echo $customers->prospect[0]->customer->contact->name; 

回答

12

您可以使用數組樣式語法按編號訪問不同的<name>元素。

$names = $customers->prospect[0]->customer->name; 

echo $names[0]; // Bob 
echo $names[1]; // Smith 

事實上,你已經這樣做是爲了<prospect>元素!

另請參閱手冊中的Basic SimpleXML Usage


如果您想根據某些標準選擇元素,那麼XPath是使用的工具。

$customer = $customers->prospect[0]->customer; 
$last_names = $customer->xpath('name[@part="last"]'); // always returns an array 
echo $last_names[0]; // Smith 
+0

+1爲漂亮的手動鏈接! – hakre 2012-08-15 20:13:34

+0

謝謝,正是我在找的! – bmanhard 2012-08-16 14:49:10

相關問題