如果需要,可以将PHP数组转换为XML或简单的XML对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如果需要,可以将PHP数组转换为XML或简单的XML对象相关的知识,希望对你有一定的参考价值。

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. }

以上是关于如果需要,可以将PHP数组转换为XML或简单的XML对象的主要内容,如果未能解决你的问题,请参考以下文章

使用 JSON 将 XML 转换为 PHP 数组正在删除某些元素的属性

XML 到 JSON 或数组? PHP

将php数组转换为xml文件

使用 PHP 将 XML 转换为关联数组

PHP递归函数将多维数组转换为xml

PHP JSON 或数组到 XML