在PHP中将多个数组转换为XML

时间:2015-01-20 03:57:18

标签: php arrays xml

我有两个数组,这是第一个:

Array
(
    [0] => BWY DL
    [1] => SP_GPON
)
//Array 1

这是最后一个:

Array
    (
        [0] => Two Way
        [1] => Ultimated
    )
//Array 2

它们都将转换为XML。我想要的格式:

<data>
   <citem>BWY DL</citem> //from array 1, array[0]
   <desc>Two Way</desc> //from array 2, array[0]
</data>
<data>
   <citem>SP_GPON</citem> //from array 1, array[1]
   <desc>Ultimated</desc> //from array 2, array[1]
</data>

我的转换代码:

$xml = new SimpleXMLElement('<data/>');
    array_walk_recursive($value, array ($xml, 'addChild'));
    array_walk_recursive($desc, array ($xml, 'addChild'));
    $output=$xml->asXML();

print_r($output); 

但它给了:

<?xml version="1.0"?>
<data>
  <BWY DL>0</BWY DL>
  <Two Way>0</Two Way>
  <SP_GPON>1</SP_GPON>
  <Ultimated>1</Ultimated>
</data>

我不知道如何将它们设置为格式。希望可以有人帮帮我。感谢。

2 个答案:

答案 0 :(得分:0)

我不知道它是否符合您的要求。 假设您的数组是固定长度的,并且格式始终相同:

function convert($array) {
    $format = "<data><citem>%s</citem><desc>%s</desc></data>";
    return sprintf($format, $array[0], $array[1]);
}

所以如果你有这样的数组:$array1 = array("citem1", "desc1"); $array2 = array("citem2", "desc2");

echo convert($array1); // <data><citem>citem1</citem><desc>desc1</desc></data>
echo convert($array2); // <data><citem>citem2</citem><desc>desc2</desc></data>

我希望它有所帮助。

答案 1 :(得分:0)

一个不专注于组合数组或利用本机数组函数的简单解决方案是for循环。

$xml = '';
$format = '<data><citem>%s</citem><desc>%s</desc></data>';
$count = count($array1);

for ($i = 0; $i < $count; ++$i) {
    $xml = sprintf($format, $array1[$i], $array2[$i]);
}

echo $xml;

注意:这假设数组的长度相同。