Tuesday, 19 January 2010

Generating an XML Document, Part One

PHP is a powerful tool to create dynamic web pages but its official documentation lacks some style.

As I am an application developper (in training) this may be just a thing that I can amend here. It's a think tank without limitations to its contents after all.

Here a first example of what I am up to right now.

Creating a dynamic web site using PHP with XML usually is about parsing existing files or writing new ones. But I happen to have come upon a problem that demands to create an XML document using PHP and then parsing it in PHP code. Some might say that this a waste of resources and it may turn out that they were right. But for the time being we'll assume this is perfectly alright and a sane thing to do - if only for educational purposes.

Generating XML from an Array

PHP has a module that makes operating on XML documents simple, hence its name SimleXML. It turns an XML document into an object providing structured access to the XML that can be stored in a variable.

To create a new XML document you need to store the XML elements and values inside a PHP array whose structure mirrors that of the XML document and then to iterate through the array while printing each element with appropriate formatting.

$wrapper = array('element1' => 'value1',
                 'element2' => 'value2');

As each element may contain multiple levels of sub-elements, so can each value be an array with its own elements and values plus even more sub-elements.

$wrapper = array('element1' => 'value1',
                 'element2' => array('element3' => 'value3',
                                     'element4' => 'value4'));

A simple foreach() functions will iterate through a simple onedimensional array but as XML documents may have multiple levels, so we need a function that iterates through multidimensional arrays. We will call this function foreacharrayparser().

function foreacharrayparser($funcarray)
     foreach($funcarray as $funcelement => $funcstring) {
          print " <$funcelement>";
          if (is_string($funcstring)) {
               print htmlentities($funcstring);
          } else {
          print "\n";

Now, in order to create the XML document, we'll have to call the function once.

print "\n";
print "

Now we should have a valid and well-formed XML document if we had done our homework for both the array structure and the remaining PHP code.

Sklar, David (2004). Learning PHP 5. Sebastopol: O'Reilly.
ISBN 978-0-596-00560-3