Last active
April 20, 2020 08:20
-
-
Save consatan/b5095c523f6179fb4d1b to your computer and use it in GitHub Desktop.
php 数组转换为 SimpleXML, php array conver to SimpleXML
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* 转换数组为 SimpleXMLElement | |
* | |
* 数组键名转换为 nodeName(value为数组时) 或 attributeName(value非array时) | |
* 数组键名为 _ 时转换为 innerText | |
* | |
* 数组值转换为 nodeValue或attribute | |
* 数组值为数组时转换为子节点 | |
* 数组值为 null 时转换为空节点 | |
* | |
* todo array.value 非数组时验证是否为标量数据类型 | |
* | |
* @param array $arr 数据数组 | |
* @param object $xml SimpleXMLElement 实例的引用 | |
* @param string $nodeName 递归中调用参数,调用时不需要提供 | |
* @return void | |
*/ | |
function arrayToXML(array $arr, \SimpleXMLElement &$xml, $nodeName = '') { | |
foreach ($arr as $key => $val) { | |
if (is_array($val)) { | |
if (is_numeric($key)) { | |
arrayToXML($val, $xml->addChild($nodeName)); | |
} else { | |
if (!isset($val[0])) { | |
arrayToXML($val, $xml->addChild($key)); | |
} else { | |
arrayToXML($val, $xml, $key); | |
} | |
} | |
} else { | |
if ($key !== '_') { | |
if (!is_null($val)) { | |
$xml->addAttribute($key, (string)$val); | |
} else { | |
$xml->addChild($key); | |
} | |
} else { | |
$xml->{0} = $val; | |
} | |
} | |
} | |
} | |
// 使用示例 | |
$arr = [ | |
'node' => [ | |
'attribute' => '123', | |
'subNode' => [ | |
'emptyNode' => null, | |
'innerTextNode' => [ | |
'_' => 'some text here', | |
'attribute' => 'attr', | |
], | |
], | |
], | |
]; | |
$root = 'documentRoot'; | |
$xml = new \SimpleXMLElement("<?xml version='1.0' encoding='UTF-8' ?><{$root}></{$root}>"); | |
arrayToXML($arr, $xml); | |
$xml = $xml->asXML(); | |
// output | |
// <?xml version="1.0" encoding="UTF-8"?> | |
// <documentRoot><node attribute="123"><subNode><emptyNode/><innerTextNode attribute="attr">some text here</innerTextNode></subNode></node></documentRoot> | |
// | |
// 去掉 xml 版本头信息和最后的换行符 | |
// $xml = preg_replace('/\r\n|\r|\n/', '', strstr($xml->asXML(), "<{$root}")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment