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.


Copy this code and paste it in your HTML
  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

You need to login to post a comment.