1.数组转xml
function arrayToXml($arr) {
$xml = "<xml>";
foreach ($arr as $key => $val){
if (is_numeric($val)){
$xml.="<$key>$val</$key>";
}
else
$xml.="<$key><![CDATA[$val]]></$key>";
}
$xml.="</xml>";
return $xml;
}
举例:
$array = [
'username' =>'zhangsan',
'sex' => '男',
'age' =>20
];
$xml = arrayToXml($array);
echo $xml;
结果如下:
<xml>
<username>
<![CDATA[zhangsan]]>
</username>
<sex>
<![CDATA[男]]>
</sex>
<age>20</age>
</xml>
2.xml转数组
function xmlToArray($xml) {
$arr = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $arr;
}
举例:
$xml = "<xml><username><![CDATA[zhangsan]]></username><sex><![CDATA[男]]></sex><age>20</age></xml>";
$arr = xmlToArray($xml);
print_r($arr);
结果如下:
Array
(
[username] => zhangsan
[sex] => 男
[age] => 20
)