我有一个这样的数组
Array
(
[351] => Array
(
[0] => Array
(
[unit_id] => Array
(
[0] => 10192
[1] => 10192
[2] => 10192
)
[born_from] => Array
(
[0] => 1980-08-21
)
[born_to] => Array
(
[0] => 2010-08-18
)
[start_date] => Array
(
[0] => 2013-02-21 17:29:00
)
[sex] => Array
(
[0] => 3
)
[id] => 351
[product_id] => 1
[name] => test1
)
)
)
我编写了一个 PHP 函数来将此数组转换为 xml
功能是
function generate_xml_from_array($array, $node_name) {
$xml = '';
if (is_array($array) || is_object($array)) {
foreach ($array as $key=>$value) {
if (is_numeric($key)) {
$key = $node_name;
}
$xml .= '<' . $key . '>' . "\n" . generate_xml_from_array($value, $node_name) . '</' . $key . '>' . "\n";
}
} else {
$xml = htmlspecialchars($array, ENT_QUOTES) . "\n";
}
return $xml;
}
function generate_valid_xml_from_array($array, $node_block='products', $node_name='node') {
$xml = '<?xml version="1.0" encoding="UTF-8" ?>' . "\n";
$xml .= '<' . $node_block . '>' . "\n";
$xml .= generate_xml_from_array($array, $node_name);
$xml .= '</' . $node_block . '>' . "\n";
return $xml;
}
$xml = generate_valid_xml_from_array($MyArray);
file_put_contents('C:/product.xml',$xml);
这给了我这样的输出
<?xml version="1.0" encoding="UTF-8" ?>
<products>
<node>
<node>
<unit_id><node>10192</node><node>10192</node><node>10192</node></unit_id>
<born_from><node>1980-08-21</node></born_from>
<born_to><node>2010-08-18</node></born_to>
<start_date><node>2013-02-21 17:29:00</node></start_date>
<sex><node>3</node></sex>
<id>351</id>
<product_id>1</product_id>
<name>test1</name>
</node>
</node>
</products>
在此输出中,有一个<node>
正在增加文件大小的任何方法来删除它<node>
,因此文件大小不会增加