欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php数组转成xml的代码

程序员文章站 2022-05-10 16:04:08
...
  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("");
  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. ?>
复制代码