simplexml, returning multiple items with the same tag

php, simplexml, xml

Solution

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

Problem

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; ```

Original source