I am trying to parse an xml document in php which is somewhat tough because the xml consists of objects within objects. Here is the xml:
<Bars>
<Bar>
<BarName>the bar name</BarName>
<bar_id>0</bar_id>
<Bartenders>
<Bartender><fname>a first name</fname><lname>a last name</lname><imageURL>an image url</imageURL><shift>2</shift></Bartender>
</Bartenders>
<Events>
<Event><EventName> event</EventName><date>08/10/1989</date></Event>
</Events>
<Specials>
<Special> Special 1</Special><Special> Special 2</Special>
</Specials>
</Bar>
Obviously there are several of these ‘bar’ objects within the bars xml element. What I am trying to figure is out how to do is parse this file, save the contents to an array, update the array with user input from an iOS app, and finally write the XML back to the page. The problem I am having is, how will I be able to save several ‘bartender’, ‘event’ and ‘special’ objects into the arrays for the respective bar? I will have to create a bartender array in the foreach array correct? Do I need to create a bar class which houses bartender, event, and special arrays?
Here is a piece of my php code thus far:
$bars = $doc->getElementsByTagName("Bar");
foreach($bars as $bar)
{
$barNames = $bar->getElementsByTagName("BarName");
$barName = $barNames->item(0)->nodeValue;
array_push($barNameArray, $barName);
echo "<b>barName:$barName</b><br>";
}
$barsArray = array();
//make any updates to the arrays as needed
for($i = 0; $i < count($barNameArray); $i++) // write an array of bar objects from the arrays created above
As you can see, I have it figured out quite easily if it’s just one type of element per bar. I can’t hardcode anything in because I won’t know how many bartenders, bars, specials, etc are posted at a given time… Thanks for your help.
Try this function to get associative array of your XML.
Usage: