XML, Php, XML_Serializer and SimpleXML

Tips and Tricks on Producing XML from MySQL

Mark Niemann-Ross
I just finished up a project that required exporting XML from a mySQL database, using php as the driving language. I approached this several different ways, and found a few things that you'll maybe find useful.

I tried the pear package called "XML_Serializer" . In this scheme, the database would be transferred to an associative array, then run through XML_Serializer to produce XML. At first, this looked promising - but it doesn't allow the creation of multiple nested elements. For example, consider the following XML:
< code >
< root >
< contact >
< name >Mark
< phoneNumbers >
< dial >503456678< /dial >
< dial >6453345567
< dial >9987765567
< /phoneNumbers >
< /contact >
< contact >
< name >bob< /name >
< phoneNumbers >
< dial >212884445< /dial >
< dial >698334557< /dial >
< dial >889765543< /dial >
< /phoneNumbers >
< /contact >
< /root >

Note there are two "contact" elements in the XML stream. XML_serializer builds an XML stream from an associative array. However, associate arrays do not allow two or more identical keys, and so are not able to build the stream described above.

A better solution is the built-in XML routines in php 5.0, specifically, the simpleXML routines . To produce the XML noted above, the php would look something like this...

// do a mysql SELECT to do a database pull (code not included here)
$dbResult = mySQL query results

// Create a seed XML file
$xmlStart = '';
$newXML = new SimpleXMLElement($xmlStart);

// do some sort of WHILE or FOREACH to iterate through the mySQL rows generated above.
while ($contactListing = mysql_fetch_array($dbResult)) {
$currentChild = $newXML->addChild("contact");
$secondChild = $currentChild->addChild("name",$contactListing['theContact']);
$secondChild = $currentChild->addChild("phoneNumbers");
foreach ($row_phonenumbers as $thevalue) {
$thirdChild = $secondChild->addChild("",$thevalue);
}
}

The code is cleaner, it doesn't require intermediating through an associative array, and best of all, doesn't require installing a separate library (assuming you are using php 5.0 or above.

Published by Mark Niemann-Ross

Mark Niemann-Ross has been explaining technology for thirty years. First as an Industrial Education teacher, then as a software developer evangelist, and most recently as a published Science Fiction Writer....   View profile

To comment, please sign in to your Yahoo! account, or sign up for a new account.