How to convert array to SimpleXML

前端 未结 30 2613
遇见更好的自我
遇见更好的自我 2020-11-21 06:52

How can I convert an array to a SimpleXML object in PHP?

相关标签:
30条回答
  • 2020-11-21 07:11

    So anyway... I took onokazu's code (thanks!) and added the ability to have repeated tags in XML, it also supports attributes, hope someone finds it useful!

     <?php
    
    function array_to_xml(array $arr, SimpleXMLElement $xml) {
            foreach ($arr as $k => $v) {
    
                $attrArr = array();
                $kArray = explode(' ',$k);
                $tag = array_shift($kArray);
    
                if (count($kArray) > 0) {
                    foreach($kArray as $attrValue) {
                        $attrArr[] = explode('=',$attrValue);                   
                    }
                }
    
                if (is_array($v)) {
                    if (is_numeric($k)) {
                        array_to_xml($v, $xml);
                    } else {
                        $child = $xml->addChild($tag);
                        if (isset($attrArr)) {
                            foreach($attrArr as $attrArrV) {
                                $child->addAttribute($attrArrV[0],$attrArrV[1]);
                            }
                        }                   
                        array_to_xml($v, $child);
                    }
                } else {
                    $child = $xml->addChild($tag, $v);
                    if (isset($attrArr)) {
                        foreach($attrArr as $attrArrV) {
                            $child->addAttribute($attrArrV[0],$attrArrV[1]);
                        }
                    }
                }               
            }
    
            return $xml;
        }
    
            $test_array = array (
              'bla' => 'blub',
              'foo' => 'bar',
              'another_array' => array (
                array('stack' => 'overflow'),
                array('stack' => 'overflow'),
                array('stack' => 'overflow'),
              ),
              'foo attribute1=value1 attribute2=value2' => 'bar',
            );  
    
            $xml = array_to_xml($test_array, new SimpleXMLElement('<root/>'))->asXML();
    
            echo "$xml\n";
            $dom = new DOMDocument;
            $dom->preserveWhiteSpace = FALSE;
            $dom->loadXML($xml);
            $dom->formatOutput = TRUE;
            echo $dom->saveXml();
        ?>
    
    0 讨论(0)
  • 2020-11-21 07:15

    Just a edit on a function above, when a key is numeric, add a prefix "key_"

    // initializing or creating array
    $student_info = array(your array data);
    
    // creating object of SimpleXMLElement
    $xml_student_info = new SimpleXMLElement("<?xml version=\"1.0\"?><student_info></student_info>");
    
    // function call to convert array to xml
    array_to_xml($student,$xml_student_info);
    
    //saving generated xml file
    $xml_student_info->asXML('file path and name');
    
    
    function array_to_xml($student_info, &$xml_student_info) {
         foreach($student_info as $key => $value) {
              if(is_array($value)) {
                if(!is_numeric($key)){
                    $subnode = $xml_student_info->addChild("$key");
                    array_to_xml($value, $subnode);
                }
                else{
                    $subnode = $xml_student_info->addChild("key_$key");
                    array_to_xml($value, $subnode);
                }
              }
              else {
                   if(!is_numeric($key)){
                        $xml_student_info->addChild("$key","$value");
                   }else{
                        $xml_student_info->addChild("key_$key","$value");
                   }
              }
         }
    }
    
    0 讨论(0)
  • 2020-11-21 07:19

    I found all of the answers to use too much code. Here is an easy way to do it:

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

    Then it's a simple matter of sending the array into the function, which uses recursion, so it will handle a multi-dimensional array:

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

    Now $xml contains a beautiful XML object based on your array exactly how you wrote it.

    print $xml->asXML();
    
    0 讨论(0)
  • 2020-11-21 07:19

    Another improvement:

    /**
    * Converts an array to XML
    *
    * @param array $array
    * @param SimpleXMLElement $xml
    * @param string $child_name
    *
    * @return SimpleXMLElement $xml
    */
    public function arrayToXML($array, SimpleXMLElement $xml, $child_name)
    {
        foreach ($array as $k => $v) {
            if(is_array($v)) {
                (is_int($k)) ? $this->arrayToXML($v, $xml->addChild($child_name), $v) : $this->arrayToXML($v, $xml->addChild(strtolower($k)), $child_name);
            } else {
                (is_int($k)) ? $xml->addChild($child_name, $v) : $xml->addChild(strtolower($k), $v);
            }
        }
    
        return $xml->asXML();
    }
    

    Usage:

    $this->arrayToXML($array, new SimpleXMLElement('<root/>'), 'child_name_to_replace_numeric_integers');
    
    0 讨论(0)
  • 2020-11-21 07:19

    IF the array is associative and keyed correctly, it would probably be easier to turn it into xml first. Something like:

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

    The other route would be to create your basic xml first, like

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

    and then for each part of your array, use something similar to my text creating loop and instead use the simplexml functions "addChild" for each node of the array.

    I'll try that out later and update this post with both versions.

    0 讨论(0)
  • 2020-11-21 07:21

    Here is php 5.2 code which will convert array of any depth to xml document:

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

    generated XML would be as:

    <?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 snippet

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

    Documentation on SimpleXMLElement::asXML used in this snippet

    0 讨论(0)
提交回复
热议问题