php - 将数组转换为 XML,两个标签都为空值
问题描述
我需要将数组转换为 XML 字符串,但如果我的数组包含某个键的空值,例如下面的“testone”和“testtwo”,我想创建打开和关闭标记。
例如在我的代码中:
$test_array = array (
'testone' => array(),
'bla' => 'blub',
'testtwo' => '',
'foo' => 'bar',
'another_array' => array (
'stack' => 'overflow',
),
);
function array_to_xml( $data, &$xml_data ) {
foreach( $data as $key => $value ) {
if( is_numeric($key) ){
$key = 'item'.$key; //dealing with <0/>..<n/> issues
}
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($test_array,$xml_data);
$result = $xml_data->asXML();
echo $result;
我得到这个结果:
<?xml version="1.0"?>
<data>
<testone/>
<bla>blub</bla>
<testtwo/>
<foo>bar</foo>
<another_array>
<stack>overflow</stack>
</another_array>
</data>
但我需要这个:
<?xml version="1.0"?>
<data>
<testone></testone>
<bla>blub</bla>
<testtwo></testtwo>
<foo>bar</foo>
<another_array>
<stack>overflow</stack>
</another_array>
</data>
解决方案
推荐阅读
- python - 如何使用 python 将 pandas 数据帧数据存储到 azure blob?
- sql-server - 休眠命名查询中“)”附近的语法不正确
- r - 使用 group_by 组合 R 中的多个字符行并汇总
- mysql - 从当前状态查询 MySQL 中获取总计数
- python - 使用 Homography 变换拼接两个图像 - 裁剪变换的图像
- sql - 已达到每个数据库的数据库副本限制。数据库 X 不能有超过 10 个并发数据库副本 (Azure SQL)
- google-cloud-platform - 如何确认我的谷歌云/API 的用户限制?
- wordpress - 如何在 WooCommerce WordPress 5.0.3 版中显示最近查看的产品
- san - 我们可以为 SAN 使用服务器 SAS 2.5" 硬盘吗?
- shell - 在 for 语句中传递命令的输出