I have created an XML file that has a structured list of franchises. Problem is that I want to grab a franchise by it's id without having to iterate throughout the whole list.
This is how I can get the attributes of the first franchise. But I want to fetch back a franchise object with an id of say '3'. I would of thought that the id would be the key but it isn't, see below:
SimpleXMLElement Object
(
[@attributes] => Array
(
[id] => 1
[name] => Franchise 1
[aid] =>
)
)
Here is how I access the first franchises attributes, but this isn't very helpful to me.
$this->xmlData->franchises->franchise->attributes()
Here is the structure of the xml
<?xml version="1.0" encoding="UTF-8"?>
<data>
<franchises>
<franchise id="1" name="Franchise 1" >
<header>
<accountId>2354435435</accountId>
</header>
<used-list>
<accountId>2354435435</accountId>
</used-list>
<used-detail>
<accountId>2354435435</accountId>
</used-detail>
<contact-us>
<accountId>2354435435</accountId>
</contact-us>
<new-detail>
<accountId>2354435435</accountId>
</new-detail>
<left-column>
<accountId>2354435435</accountId>
</left-column>
<new-list>
<accountId>2354435435</accountId>
</new-list>
<offer-detail>
<accountId>2354435435</accountId>
</offer-detail>
<popup>
<accountId>2354435435</accountId>
</popup>
</franchise>
<franchise id="2" name="Franchise 2" >
<header>
<accountId>2354435435</accountId>
</header>
<used-list>
<accountId>2354435435</accountId>
</used-list>
<used-detail>
<accountId>2354435435</accountId>
</used-detail>
<contact-us>
<accountId>2354435435</accountId>
</contact-us>
<new-detail>
<accountId>2354435435</accountId>
</new-detail>
<left-column>
<accountId>2354435435</accountId>
</left-column>
<new-list>
<accountId>2354435435</accountId>
</new-list>
<offer-detail>
<accountId>2354435435</accountId>
</offer-detail>
<popup>
<accountId>2354435435</accountId>
</popup>
</franchise>
</franchises>
</data>
Help would be greatly appreciated.
Look at xpath. You can retrieve a specific node by attribute like this :
$result = $xml->xpath("//franchises/franchise[@id='2']");