php xml 文件的简单操作, 包括正向和逆向操作:
读取 xml 文件,解释为 SampleXMLElement 对象;
将数组转换为 xml 文件
解析 xml 内容:
/**
* $return_type: default is '', return xml object,
* if 'json' return json type;
* else if 'array' return array type;
*/
function parse_xml($xml_string, $return_type = '') {
// try {
$xml = simplexml_load_string($xml_string, "SimpleXMLElement", LIBXML_NOCDATA);
if ($return_type == '') {
return $xml;
}
$json = json_encode($xml);
if ($return_type == 'json') {
return $json;
}
$array = json_decode($json,TRUE);
return $array;
// }
// catch (Exception $e) {
// }
}
数组转换为 xml:
function array_to_xml($array) {
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?>'.'<NewDriver/>');
foreach($array as $driver) {
$node_driver = $xml->addChild('Driver');
$node_driver->addAttribute('HardwareId', $driver['match_device']['HardwareId']);
}
return $xml->asXML();
}
如果 xml 无需 atrribute,而且数组是键值对,可以使用以下方法:
function array_to_xml($array) {
$xml = new SimpleXMLElement('<NewDriver/>');
array_walk_recursive($array, array ($xml, 'addChild'));
// print $xml->asXML();
return $xml->asXML();
}
程序中如果涉及到读取或写入文件,可以参考:
字符串写入文件,读取文件到字符串
https://www.geeksforgeeks.org/how-to-convert-array-to-simplexml-in-php/