[英]Generate XML file in PHP
I am trying to generate the XML file from the PHP array. 我正在尝试从PHP数组生成XML文件。 Everything seems working quite well, but I cannot remove the parent node. 一切看起来都很好,但是我无法删除父节点。
This is how my array looks like: 这是我的数组的样子:
And this is the generated XML file 这是生成的XML文件
As you can see I have some "items" inside the parent node named "item". 如您所见,我在名为“ item”的父节点中有一些“ items”。
I just want to know, how I can remove the parent node named "item" and leave just structure like: 我只想知道,如何删除名为“ item”的父节点并保留如下结构:
My PHP code: 我的PHP代码:
function array_to_xml( $data, $xml_data ) {
foreach( $data as $key => $value ) {
if( is_numeric($key) ){
$key = 'item';
}
if( is_array($value) ) {
$subnode = $xml_data->addChild($key);
array_to_xml($value, $subnode);
} else {
$xml_data->addChild("$key",htmlspecialchars("$value"));
}
}
}
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');
array_to_xml($newArrayXml,$xml_data);
//saving generated xml file;
$result = $xml_data->asXML('list.xml')
When I ran the above code using the following array, it output what you are looking for: 当我使用以下数组运行上述代码时,它将输出您要查找的内容:
$newArrayXml = array(
2410687 => array('id' => 2410687),
2440673 => array('id' => 2440673),
2415709 => array('id' => 2415709),
2445675 => array('id' => 2445675)
);
// var_dump($newArrayXml);exit;
function array_to_xml( $data, $xml_data ) {
foreach( $data as $key => $value ) {
if( is_numeric($key) ){
$key = 'item';
}
if( is_array($value) ) {
$subnode = $xml_data->addChild($key);
array_to_xml($value, $subnode);
} else {
$xml_data->addChild("$key",htmlspecialchars("$value"));
}
}
}
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');
array_to_xml($newArrayXml,$xml_data);
//saving generated xml file;
$result = $xml_data->asXML('list.xml');
Result: 结果:
<?xml version="1.0"?>
<data>
<item><id>2410687</id></item>
<item><id>2440673</id></item>
<item><id>2415709</id></item>
<item><id>2445675</id></item>
</data>
Perhaps the issue is with your array. 也许问题出在您的阵列上。 It shows array(1)
in your photo, which would imply you have an extra array: 它在您的照片中显示array(1)
,这意味着您还有一个额外的数组:
$newArrayXml = array(array(
2410687 => array('id' => 2410687),
2440673 => array('id' => 2440673),
2415709 => array('id' => 2415709),
2445675 => array('id' => 2445675)
));
This generates the output that you did not want. 这将生成您不需要的输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.