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


当前回答

下面是php 5.2代码,将数组的任何深度转换为xml文档:

Array
(
    ['total_stud']=> 500
    [0] => Array
        (
            [student] => Array
                (
                    [id] => 1
                    [name] => abc
                    [address] => Array
                        (
                            [city]=>Pune
                            [zip]=>411006
                        )                       
                )
        )
    [1] => Array
        (
            [student] => Array
                (
                    [id] => 2
                    [name] => xyz
                    [address] => Array
                        (
                            [city]=>Mumbai
                            [zip]=>400906
                        )   
                )

        )
)

生成的XML如下所示:

<?xml version="1.0"?>
<student_info>
    <total_stud>500</total_stud>
    <student>
        <id>1</id>
        <name>abc</name>
        <address>
            <city>Pune</city>
            <zip>411006</zip>
        </address>
    </student>
    <student>
        <id>1</id>
        <name>abc</name>
        <address>
            <city>Mumbai</city>
            <zip>400906</zip>
        </address>
    </student>
</student_info>

PHP代码片段

<?php
// function defination to convert array to xml
function array_to_xml( $data, &$xml_data ) {
    foreach( $data as $key => $value ) {
        if( is_array($value) ) {
            if( is_numeric($key) ){
                $key = 'item'.$key; //dealing with <0/>..<n/> issues
            }
            $subnode = $xml_data->addChild($key);
            array_to_xml($value, $subnode);
        } else {
            $xml_data->addChild("$key",htmlspecialchars("$value"));
        }
     }
}

// initializing or creating array
$data = array('total_stud' => 500);

// creating object of SimpleXMLElement
$xml_data = new SimpleXMLElement('<?xml version="1.0"?><data></data>');

// function call to convert array to xml
array_to_xml($data,$xml_data);

//saving generated xml file; 
$result = $xml_data->asXML('/file/path/name.xml');

?>

本代码段中使用的SimpleXMLElement::asXML文档

其他回答

如果数组是关联的并且键是正确的,那么首先将它转换为xml可能会更容易。喜欢的东西:

  function array2xml ($array_item) {
    $xml = '';
    foreach($array_item as $element => $value)
    {
        if (is_array($value))
        {
            $xml .= "<$element>".array2xml($value)."</$element>";
        }
        elseif($value == '')
        {
            $xml .= "<$element />";
        }
        else
        {
            $xml .= "<$element>".htmlentities($value)."</$element>";
        }
    }
    return $xml;
}

$simple_xml = simplexml_load_string(array2xml($assoc_array));

另一种方法是首先创建基本的xml,例如

$simple_xml = simplexml_load_string("<array></array>");

然后对于数组的每个部分,使用类似于我的文本创建循环的东西,而不是使用simplexml函数“addChild”用于数组的每个节点。

稍后我将尝试使用这两个版本来更新这篇文章。

// 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); } } }

这里提供的答案仅将数组转换为带节点的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>
*/
?>
<?php
function array_to_xml(array $arr, SimpleXMLElement $xml)
{
    foreach ($arr as $k => $v) {
        is_array($v)
            ? array_to_xml($v, $xml->addChild($k))
            : $xml->addChild($k, $v);
    }
    return $xml;
}

$test_array = array (
    'bla' => 'blub',
    'foo' => 'bar',
    'another_array' => array (
        'stack' => 'overflow',
    ),
);

echo array_to_xml($test_array, new SimpleXMLElement('<root/>'))->asXML();

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

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);