simplexml, returning multiple items with the same tag

与世无争的帅哥 提交于 2019-12-10 20:38:17

问题


I have the following XML file loaded into php simplexml.

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

using

$customers = new SimpleXMLElement($xmlstring); 

This will return "Bob" but how do I return the last name?

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

回答1:


You can access the different <name> elements by number, using array-style syntax.

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

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

In fact, you're already doing it for the <prospect> element!

See also Basic SimpleXML Usage in the manual.


If you want to select elements based on some criteria, then XPath is the tool to use.

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


来源:https://stackoverflow.com/questions/11976453/simplexml-returning-multiple-items-with-the-same-tag

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!