首页 > 解决方案 > 将数组转换为 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>

标签: phparraysxml

解决方案


推荐阅读