如何将数组转换为PHP中的SimpleXML对象?


当前回答

// Structered array for XML convertion. $data_array = array( array( '#xml_tag' => 'a', '#xml_value' => '', '#tag_attributes' => array( array( 'name' => 'a_attr_name', 'value' => 'a_attr_value', ), ), '#subnode' => array( array( '#xml_tag' => 'aa', '#xml_value' => 'aa_value', '#tag_attributes' => array( array( 'name' => 'aa_attr_name', 'value' => 'aa_attr_value', ), ), '#subnode' => FALSE, ), ), ), array( '#xml_tag' => 'b', '#xml_value' => 'b_value', '#tag_attributes' => FALSE, '#subnode' => FALSE, ), array( '#xml_tag' => 'c', '#xml_value' => 'c_value', '#tag_attributes' => array( array( 'name' => 'c_attr_name', 'value' => 'c_attr_value', ), array( 'name' => 'c_attr_name_1', 'value' => 'c_attr_value_1', ), ), '#subnode' => array( array( '#xml_tag' => 'ca', '#xml_value' => 'ca_value', '#tag_attributes' => FALSE, '#subnode' => array( array( '#xml_tag' => 'caa', '#xml_value' => 'caa_value', '#tag_attributes' => array( array( 'name' => 'caa_attr_name', 'value' => 'caa_attr_value', ), ), '#subnode' => FALSE, ), ), ), ), ), ); // creating object of SimpleXMLElement $xml_object = new SimpleXMLElement('<?xml version=\"1.0\"?><student_info></student_info>'); // function call to convert array to xml array_to_xml($data_array, $xml_object); // saving generated xml file $xml_object->asXML('/tmp/test.xml'); /** * Converts an structured PHP array to XML. * * @param Array $data_array * The array data for converting into XML. * @param Object $xml_object * The SimpleXMLElement Object * * @see https://gist.github.com/drupalista-br/9230016 * */ function array_to_xml($data_array, &$xml_object) { foreach($data_array as $node) { $subnode = $xml_object->addChild($node['#xml_tag'], $node['#xml_value']); if ($node['#tag_attributes']) { foreach ($node['#tag_attributes'] as $tag_attributes) { $subnode->addAttribute($tag_attributes['name'], $tag_attributes['value']); } } if ($node['#subnode']) { array_to_xml($node['#subnode'], $subnode); } } }

其他回答

下面讨论名称空间。在本例中,构造包装器以包含名称空间定义,并将其传递给函数。使用冒号来标识命名空间。

测试数组

$inarray = [];
$inarray['p:apple'] = "red";
$inarray['p:pear'] = "green";
$inarray['p:peach'] = "orange";
$inarray['p1:grocers'] = ['p1:local' => "cheap", 'p1:imported' => "expensive"];


$xml = new SimpleXMLElement( '<p:wrapper xmlns:p="http://namespace.org/api" xmlns:p1="http://namespace.org/api2 /> ');

array_to_xml($xml,$inarray); 




function array_to_xml(SimpleXMLElement $object, array $data)
{   
    $nslist = $object->getDocNamespaces();

    foreach ($data as $key => $value)
    {   
        $nspace = null;
        $keyparts = explode(":",$key,2);
        if ( count($keyparts)==2) 
            $nspace = $nslist[$keyparts[0]];

        if (is_array($value))
        {   
            $key = is_numeric($key) ? "item$key" : $key;
            $new_object = $object->addChild($key,null,$nspace);
            array_to_xml($new_object, $value);
        }   
        else
        {   
            $key = is_numeric($key) ? "item$key" : $key;
            $object->addChild($key, $value,$nspace);
        }   
    }   
}   

我发现所有的答案都是使用过多的代码。这里有一个简单的方法:

function to_xml(SimpleXMLElement $object, array $data)
{   
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            $new_object = $object->addChild($key);
            to_xml($new_object, $value);
        } else {
            // if the key is an integer, it needs text with it to actually work.
            if ($key != 0 && $key == (int) $key) {
                $key = "key_$key";
            }

            $object->addChild($key, $value);
        }   
    }   
}   

然后,将数组发送到使用递归的函数中就很简单了,因此它将处理多维数组:

$xml = new SimpleXMLElement('<rootTag/>');
to_xml($xml, $my_array);

现在$xml包含了一个漂亮的xml对象,它完全基于您编写数组的方式。

print $xml->asXML();

这里提供的答案仅将数组转换为带节点的XML,不能设置属性。我已经编写了一个php函数,允许您将数组转换为php,并为xml中的特定节点设置属性。这里的缺点是您必须以很少约定的特定方式构造数组(仅当您想使用属性时)

下面的示例也允许您用XML设置属性。

来源可以在这里找到: https://github.com/digitickets/lalit/blob/master/src/Array2XML.php

<?php    
$books = array(
    '@attributes' => array(
        'type' => 'fiction'
    ),
    'book' => array(
        array(
            '@attributes' => array(
                'author' => 'George Orwell'
            ),
            'title' => '1984'
        ),
        array(
            '@attributes' => array(
                'author' => 'Isaac Asimov'
            ),
            'title' => 'Foundation',
            'price' => '$15.61'
        ),
        array(
            '@attributes' => array(
                'author' => 'Robert A Heinlein'
            ),
            'title' => 'Stranger in a Strange Land',
            'price' => array(
                '@attributes' => array(
                    'discount' => '10%'
                ),
                '@value' => '$18.00'
            )
        )
    )
);
/* creates 
<books type="fiction">
  <book author="George Orwell">
    <title>1984</title>
  </book>
  <book author="Isaac Asimov">
    <title>Foundation</title>
    <price>$15.61</price>
  </book>
  <book author="Robert A Heinlein">
    <title>Stranger in a Strange Land</title>
    <price discount="10%">$18.00</price>
  </book>
</books>
*/
?>

这是我的入口,简单而干净。

function array2xml($array, $xml = false){
    if($xml === false){
        $xml = new SimpleXMLElement('<root/>');
    }
    foreach($array as $key => $value){
        if(is_array($value)){
            array2xml($value, $xml->addChild($key));
        }else{
            $xml->addChild($key, $value);
        }
    }
    return $xml->asXML();
}


header('Content-type: text/xml');
print array2xml($array);

我的答案,拼凑别人的答案。这应该可以纠正无法补偿数字键的错误:

function array_to_xml($array, $root, $element) {
    $xml = new SimpleXMLElement("<{$root}/>");
    foreach ($array as $value) {
        $elem = $xml->addChild($element);
        xml_recurse_child($elem, $value);
    }
    return $xml;
}

function xml_recurse_child(&$node, $child) {
    foreach ($child as $key=>$value) {
        if(is_array($value)) {
            foreach ($value as $k => $v) {
                if(is_numeric($k)){
                    xml_recurse_child($node, array($key => $v));
                }
                else {
                    $subnode = $node->addChild($key);
                    xml_recurse_child($subnode, $value);
                }
            }
        }
        else {
            $node->addChild($key, $value);
        }
    }   
}

array_to_xml()函数假定数组首先由数字键组成。如果数组有一个初始元素,则可以从array_to_xml()函数中删除foreach()和$elem语句,只传递$xml。