您可以使用PHP的内置函数simplexml_load_string()
将数组转换为XML。以下是一个示例代码:
function array_to_xml($array, &$xml) {
foreach($array as $key => $value) {
if(is_array($value)) {
if(!is_numeric($key)){
$subnode = $xml->addChild("$key");
array_to_xml($value, $subnode);
}else{
$subnode = $xml->addChild("item$key");
array_to_xml($value, $subnode);
}
}else{
$xml->addChild("$key",htmlspecialchars("$value"));
}
}
}
$array = array(
'person' => array(
'name' => 'John Doe',
'age' => 30,
'email' => 'johndoe@example.com'
),
'colors' => array('red', 'green', 'blue')
);
$xml = new SimpleXMLElement('<root/>');
array_to_xml($array, $xml);
echo $xml->asXML();
这将输出以下XML:
<root>
<person>
<name>John Doe</name>
<age>30</age>
<email>johndoe@example.com</email>
</person>
<colors>
<item0>red</item0>
<item1>green</item1>
<item2>blue</item2>
</colors>
</root>
上一篇:php多维数组比较不同
下一篇:php判断数组没有键
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站