Home >Backend Development >PHP Tutorial >Code to convert php array to xml

Code to convert php array to xml

WBOY
WBOYOriginal
2016-07-25 09:04:17898browse
  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. if ($xml == null)
  20. {
  21. $xml = simplexml_load_string("<$rootNodeName />");
  22. }
  23. // loop through the data passed in.
  24. foreach($data as $key => $value)
  25. {
  26. // no numeric keys in our xml please!
  27. if (is_numeric($key))
  28. {
  29. // make string key...
  30. $key = "unknownNode_". (string) $key;
  31. }
  32. // replace anything not alpha numeric
  33. $key = preg_replace('/[^a-z]/i', '', $key);
  34. // if there is another array found recrusively call this function
  35. if (is_array($value))
  36. {
  37. $node = $xml->addChild($key);
  38. // recrusive call.
  39. ArrayToXML::toXml($value, $rootNodeName, $node);
  40. }
  41. else
  42. {
  43. // add single node.
  44. $value = htmlentities($value);
  45. $xml->addChild($key,$value);
  46. }
  47. }
  48. // pass back as string. or simple xml object if you want!
  49. return $xml->asXML();
  50. }
  51. }
复制代码

2、自己写的php数组转xml的代码

  1. function arrtoxml($arr,$dom=0,$item=0){
  2. if (!$dom){
  3. $dom = new DOMDocument("1.0");
  4. }
  5. if(!$item){
  6. $item = $dom->createElement("root");
  7. $dom->appendChild($item);
  8. }
  9. foreach ($arr as $key=>$val){
  10. $itemx = $dom->createElement(is_string($key)?$key:"item");
  11. $item->appendChild($itemx);
  12. if (!is_array($val)){
  13. $text = $dom->createTextNode($val);
  14. $itemx->appendChild($text);
  15. }else {
  16. arrtoxml($val,$dom,$itemx);
  17. }
  18. }
  19. return $dom->saveXML();
  20. }
  21. ?>
复制代码


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn