simpleXML,返回具有相同标记的多个项目


simplexml, returning multiple items with the same tag

我将以下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