Learn an easy way to parse XML and output it the way you want by using the simpleXML extensions in PHP5. Murray outlines the 3 main elements of an XML document and how to replace them with your own non-template data and how to build an array of all the tags put in the document.
Now we’ll use array_keys() to get all the names of the tags from the $load array we load that into $tags (3). Then we run the $tags array through a loop to get the value of each of the array keys (4). Now we build our new list of the actual tags to replace (this is a little easier than searching the XML document to find all the replaceable tags) (5). Now we use another built in function that’s just like array_keys() but instead of operating on the keys it operates on the values. It’s surprisingly named array_values() (6). Then we put it all together and run it through srt_replace() which with loop through the arrays that we pass to it (7). Str_replace() will return a string will all occurrences of $newtags in $string replaces with $loads respectively.
That’s about it for the replace() function. Now let's move on to how we plan on getting the XML elements to the replace() function.
Give it a little class:
Now, for the part that you probably started reading this article for, simpleXML. SimpleXML works a lot like your average PHP class. You simply set simplexml_load_file() to the value of a variable and call a file name with it to load the XML document into the script then you use the -> operator to call each element of the XML file, such as in the following snippet that uses our template.xml.
<? //load the template.xml file. $template = simpleXML_load_file(template.xml); //load the header element as a string $header = $template->header; //output the header element echo $header; ?>
Go ahead and try that, then check the page source in your browser and you’ll see the exact html that’s in the header element of the template.xml file. Compare that to doing the same thing in PHP4 and you’ll understand why it’s called simpleXML. As you can see simplexml_load_file() basically loads the XML file into the $template variable and sets it up as if it’s a class and you call each element as if it were a class’s variable. Pretty simple isn’t it, hence the name simpleXML. Now that you know how simpleXML is going to help us load the xml file, we’re going to talk about how to build it all to easily load your XML template file into your script, then replace the tags, without have a bunch of the $template-> lines.