We Recommend

Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems Wicked Cool PHP: Real-World Scripts That Solve Difficult Problems
Wicked Cool PHP contains a wide variety of scripts to process credit cards, check the validity of email addresses, template HTML, and serve dynamic images and text.


Posted By

djdykes on 08/08/07


Tagged

php array xml simplexml


Versions (?)


Convert PHP Array to XML or Simple XML Object if you wish


Published in: PHP 


Was fiddling around at work one day thought this might be useful.

  1. class ArrayToXML
  2. {
  3. /**
  4. * The main function for converting to an XML document.
  5. * Pass in a multi dimensional array and this recrusively loops through and builds up an XML document.
  6. *
  7. * @param array $data
  8. * @param string $rootNodeName - what you want the root node to be - defaultsto data.
  9. * @param SimpleXMLElement $xml - should only be used recursively
  10. * @return string XML
  11. */
  12. public static function toXml($data, $rootNodeName = 'data', $xml=null)
  13. {
  14. // turn off compatibility mode as simple xml throws a wobbly if you don't.
  15. if (ini_get('zend.ze1_compatibility_mode') == 1)
  16. {
  17. ini_set ('zend.ze1_compatibility_mode', 0);
  18. }
  19.  
  20. if ($xml == null)
  21. {
  22. $xml = simplexml_load_string("<?xml version='1.0' encoding='utf-8'?><$rootNodeName />");
  23. }
  24.  
  25. // loop through the data passed in.
  26. foreach($data as $key => $value)
  27. {
  28. // no numeric keys in our xml please!
  29. if (is_numeric($key))
  30. {
  31. // make string key...
  32. $key = "unknownNode_". (string) $key;
  33. }
  34.  
  35. // replace anything not alpha numeric
  36. $key = preg_replace('/[^a-z]/i', '', $key);
  37.  
  38. // if there is another array found recrusively call this function
  39. if (is_array($value))
  40. {
  41. $node = $xml->addChild($key);
  42. // recrusive call.
  43. ArrayToXML::toXml($value, $rootNodeName, $node);
  44. }
  45. else
  46. {
  47. // add single node.
  48. $value = htmlentities($value);
  49. $xml->addChild($key,$value);
  50. }
  51.  
  52. }
  53. // pass back as string. or simple xml object if you want!
  54. return $xml->asXML();
  55. }
  56. }

Report this snippet 

Comments

RSS Icon Subscribe to comments
Posted By: maverickblair on January 22, 2008

how do you implement this? where are you connecting to the database table?

Posted By: visual77 on September 24, 2008

This is not a bad little snippet of code, but it has a few drawbacks.

First, it uses Simple XML, which is easier to use than DOMDocument, but is lacking DOMXpath and requires a bit of conversion before you can use it with the XSLTProcessor.

Second, it only lets you fire it off once before returning an XML tree. Further modification is difficult, and would require running it multiple times and then combining the results.

Third, it only supports arrays. Trying to pass a string, can only work if it is an element of the array. If you passed an array of DOMElements, or a mixed collection, or anything besides multidimensional arrays containing only arrays, strings, nulls, or ints, it'll crash.

Fourth, if the array keys are all numeric, it will attempt to add an invalid node to the tree and crash ungracefully.

Fifth, it has no built in support for an XSL driven website and can only be used loosely in conjuction with PHP's XSLTProcessor to that effect.

For an object that fixes all of these issues, check out the DOMi project at http://domi.sourceforge.net - this object is an improved version of DOMDocument, combined with DOMXpath and XSLTProcessor that is built to allow most PHP data structures to be converted to an XML tree flawlessly, lets you run that function multiple times to build up elaborate XML trees, and is designed with XSLTProcessor in mind, and lets you convert from an array to an XML tree and render through the XSLTProcessor in as few as three lines.

Posted By: visual77 on September 24, 2008

In response to my previous comment - ignore item #4. Rereading the code shows me that I missed the section that replaces numeric keys with a string value. However, it will behave oddly. This code replaces "4" with "unknownNode_4" right before removing all non alpha characters, which converts it to "unknownNode".

Posted By: hradek on October 1, 2008

Hi there, this is an excellent snippet and does the job fantastically when you want to accomplish the simple task of converting an array to XML.

Firstly, make sure you pass the $xml as a reference otherwise the stuff inside the recursive. Here is what I mean:

private function convertArray2xml($dataArray, $rootNodeName = 'dataSet', &$xml = null)

Secondly, you can't check if a variable is null the way you do. Here is how it should look:

if(isnull($xml))
{
        $xml = simplexml_load_string("");
}

Finally, to implement this in your code can be very straight forward. After you connect to your database and get back your result set as an array run it through this function. I took it out of this wrapper class and stuck it into my MySQL DBI.

You need to login to post a comment.