资源: PHP官方网站 - SimpleXMLElement文档
如果你认为这行代码中存在错误:
$xml = iconv("UTF-16", "UTF-8", $xml)
然后将其更改为以下内容,因为 $xml 可能不是 "UTF-16" 格式:
$xml = iconv(mb_detect_encoding($xml), "UTF-8", $xml)
保存XML文件的方法如下:
//saving generated xml file
$xml_student_info->asXML('file path and name')
导入XML文件的步骤:
$url = "http://www.domain.com/users/file.xml"
$xml = simplexml_load_string(file_get_contents($url))
如果您有以下的数组:
$test_array = array (
'bla' => 'blub',
'foo' => 'bar',
'another_array' => array (
'stack' => 'overflow',
),
);
如果你希望将其转换为以下XML格式:
<?xml version="1.0"?>
<main_node>
<bla>blub</bla>
<foo>bar</foo>
<another_array>
<stack>overflow</stack>
</another_array>
</main_node>
下面是 PHP 代码:
<?php
$test = array (
'bla' => 'blub',
'foo' => 'bar',
'another_array' => array (
'stack' => 'overflow',
),
);
$xml_test = new SimpleXMLElement("<?xml version=\"1.0\"?><main_node></main_node>");
array_to_xml($test,$xml_test);
function array_to_xml($test, &$xml_test) {
foreach($test as $key => $value) {
if(is_array($value)) {
if(!is_numeric($key)){
$subnode = $xml_test->addChild("$key");
array_to_xml($value, $subnode);
}
else{
$subnode = $xml_test->addChild("item$key");
array_to_xml($value, $subnode);
}
}
else {
$xml_test->addChild("$key","$value");
}
}
}
/we finally print it out
print $xml_test->asXML();
?>