我将以下XML文件加载到php simplexml中。
<adf>
<prospect>
<customer>
<name part="first">Bob</name>
<name part="last">Smith</name>
</customer>
</prospect>
</adf>
用
$customers = new SimpleXMLElement($xmlstring);
这将返回"Bob",但如何返回姓氏?
echo $customers->prospect[0]->customer->contact->name;
您可以使用
数组样式语法按编号访问不同的<name>
元素。
$names = $customers->prospect[0]->customer->name;
echo $names[0]; // Bob
echo $names[1]; // Smith
事实上,你已经在为<prospect>
元素这样做了!
另请参阅手册中的 Basic SimpleXML 用法。
如果要根据某些条件选择元素,则 XPath 是要使用的工具。
$customer = $customers->prospect[0]->customer;
$last_names = $customer->xpath('name[@part="last"]'); // always returns an array
echo $last_names[0]; // Smith