How to convert array to SimpleXML

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

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

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

    I would have commented the second most voted answer, because it doesn't preserve structure and generates bad xml if there is numerically indexed inner arrays.

    I developed my own version based on it, because I needed simple converter between json and xml regardless of the structure of data. My version preserves numeric key information and structure of the original array. It creates elements for the numerically indexed values by wrapping values to value -named elements with key-attribute that contains numerical key.

    For example

    array('test' => array(0 => 'some value', 1 => 'other'))

    converts to

    <test><value key="0">some value</value><value key="1">other</value></test>

    My version of array_to_xml -function (hope it helps somebody :)

    function array_to_xml($arr, &$xml) {
        foreach($arr as $key => $value) {
            if(is_array($value)) {
                if(!is_numeric($key)){
                    $subnode = $xml->addChild("$key");
                } else {
                    $subnode = $xml->addChild("value");
                    $subnode->addAttribute('key', $key);                    
                }
                array_to_xml($value, $subnode);
            }
            else {
                if (is_numeric($key)) {
                    $xml->addChild("value", $value)->addAttribute('key', $key);
                } else {
                    $xml->addChild("$key",$value);
                }
            }
        }
    }   
    
    0 讨论(0)
  • 2020-11-21 07:08

    I use a couple of functions that I wrote a while back to generate the xml to pass back and forth from PHP and jQuery etc... Neither use any additional frameworks just purely generates a string that can then be used with SimpleXML (or other framework)...

    If it's useful to anyone, please use it :)

    function generateXML($tag_in,$value_in="",$attribute_in=""){
        $return = "";
        $attributes_out = "";
        if (is_array($attribute_in)){
            if (count($attribute_in) != 0){
                foreach($attribute_in as $k=>$v):
                    $attributes_out .= " ".$k."=\"".$v."\"";
                endforeach;
            }
        }
        return "<".$tag_in."".$attributes_out.((trim($value_in) == "") ? "/>" : ">".$value_in."</".$tag_in.">" );
    }
    
    function arrayToXML($array_in){
        $return = "";
        $attributes = array();
        foreach($array_in as $k=>$v):
            if ($k[0] == "@"){
                // attribute...
                $attributes[str_replace("@","",$k)] = $v;
            } else {
                if (is_array($v)){
                    $return .= generateXML($k,arrayToXML($v),$attributes);
                    $attributes = array();
                } else if (is_bool($v)) {
                    $return .= generateXML($k,(($v==true)? "true" : "false"),$attributes);
                    $attributes = array();
                } else {
                    $return .= generateXML($k,$v,$attributes);
                    $attributes = array();
                }
            }
        endforeach;
        return $return;
    }   
    

    Love to all :)

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

    Here's a function that did the trick for me:

    Just call it with something like

    echo arrayToXml("response",$arrayIWantToConvert);
    function arrayToXml($thisNodeName,$input){
            if(is_numeric($thisNodeName))
                throw new Exception("cannot parse into xml. remainder :".print_r($input,true));
            if(!(is_array($input) || is_object($input))){
                return "<$thisNodeName>$input</$thisNodeName>";
            }
            else{
                $newNode="<$thisNodeName>";
                foreach($input as $key=>$value){
                    if(is_numeric($key))
                        $key=substr($thisNodeName,0,strlen($thisNodeName)-1);
                    $newNode.=arrayToXml3($key,$value);
                }
                $newNode.="</$thisNodeName>";
                return $newNode;
            }
        }
    
    0 讨论(0)
  • 2020-11-21 07:09

    Most of the above answers are correct. However, I came up with this answer which solves the array_walk_recursive compatibility issue and also the numerical keys problem. It also passed all the tests I made:

    function arrayToXML(Array $array, SimpleXMLElement &$xml) {
    
        foreach($array as $key => $value) {
    
            // None array
            if (!is_array($value)) {
                (is_numeric($key)) ? $xml->addChild("item$key", $value) : $xml->addChild($key, $value);
                continue;
            }   
    
            // Array
            $xmlChild = (is_numeric($key)) ? $xml->addChild("item$key") : $xml->addChild($key);
            arrayToXML($value, $xmlChild);
        }
    }   
    

    I have also added a test class for this which you may find useful:

    class ArrayToXmlTest extends PHPUnit_Framework_TestCase {
    
        public function setUp(){ }
        public function tearDown(){ }
    
        public function testFuncExists() {
            $this->assertTrue(function_exists('arrayToXML'));
        }
    
        public function testFuncReturnsXml() {
            $array = array(
                'name' => 'ardi',
                'last_name' => 'eshghi',
                'age' => 31,
                'tel' => '0785323435'
            );
    
            $xmlEl =  new SimpleXMLElement('<root/>');
            arrayToXml($array, $xmlEl);
    
            $this->assertTrue($xmlEl instanceOf SimpleXMLElement);
        }
    
        public function testAssocArrayToXml() {
    
            $array = array(
                'name' => 'ardi',
                'last_name' => 'eshghi',
                'age' => 31,
                'tel' => '0785323435'
            );
    
            $expectedXmlEl = new SimpleXMLElement('<root/>'); 
            $expectedXmlEl->addChild('name', $array['name']);
            $expectedXmlEl->addChild('last_name', $array['last_name']);
            $expectedXmlEl->addChild('age', $array['age']);
            $expectedXmlEl->addChild('tel', $array['tel']);
    
            $actualXmlEl =  new SimpleXMLElement('<root/>');
            arrayToXml($array, $actualXmlEl);
    
            $this->assertEquals($expectedXmlEl->asXML(), $actualXmlEl->asXML());
        }
    
        public function testNoneAssocArrayToXml() {
    
            $array = array(
                'ardi',
                'eshghi',
                31,
                '0785323435'
            );
    
            // Expected xml value
            $expectedXmlEl = new SimpleXMLElement('<root/>'); 
            foreach($array as $key => $value)
                $expectedXmlEl->addChild("item$key", $value);
    
            // What the function produces       
            $actualXmlEl =  new SimpleXMLElement('<root/>');
            arrayToXml($array, $actualXmlEl);
    
            $this->assertEquals($expectedXmlEl->asXML(), $actualXmlEl->asXML());
        }
    
        public function testNestedMixArrayToXml() {
    
            $testArray = array(
                "goal",
                "nice",
                "funny" => array(
                    'name' => 'ardi',
                    'tel'   =>'07415517499',
                    "vary",
                    "fields" => array(
                        'small',
                        'email' => 'ardi.eshghi@gmail.com'
                    ),
    
                    'good old days'
    
                ),
    
                "notes" => "come on lads lets enjoy this",
                "cast" => array(
                    'Tom Cruise',
                    'Thomas Muller' => array('age' => 24)
                )
            );
    
            // Expected xml value
            $expectedXmlEl = new SimpleXMLElement('<root/>'); 
            $expectedXmlEl->addChild('item0', $testArray[0]);
            $expectedXmlEl->addChild('item1', $testArray[1]);
            $childEl = $expectedXmlEl->addChild('funny');
            $childEl->addChild("name", $testArray['funny']['name']);
            $childEl->addChild("tel", $testArray['funny']['tel']);
            $childEl->addChild("item0", "vary");
            $childChildEl = $childEl->addChild("fields");
            $childChildEl->addChild('item0', 'small');
            $childChildEl->addChild('email', $testArray['funny']['fields']['email']);
            $childEl->addChild("item1", 'good old days');
            $expectedXmlEl->addChild('notes', $testArray['notes']);
            $childEl2 = $expectedXmlEl->addChild('cast');
            $childEl2->addChild('item0', 'Tom Cruise');
            $childChildEl2 = $childEl2->addChild('Thomas Muller');
            $childChildEl2->addChild('age', $testArray['cast']['Thomas Muller']['age']);
    
            // What the function produces       
            $actualXmlEl = new SimpleXMLElement('<root/>');
            arrayToXml($testArray, $actualXmlEl);
    
            $this->assertEquals($expectedXmlEl->asXML(), $actualXmlEl->asXML());
        }
    }      
    
    0 讨论(0)
  • 2020-11-21 07:09

    You may use xmlrpc_encode to create a xml from array if a verbose xml is not a problem. www.php.net/xmlrpc_encode

    be careful the xml created differs in case you use associative and/or numeric keys

    <?php
    // /params/param/value/struct/member
    // there is a tag "member" for each element
    // "member" contains a tag "name". its value is the associative key
    $xml1 = xmlrpc_encode(array('a'=>'b','c'=>'d'));
    $simplexml1 = simplexml_load_string($xml1);
    print_r($xml1);
    print_r($simplexml1);
    
    // /params/param/value/array/data
    // there is a tag "data" for each element
    // "data" doesn't contain the tag "name"
    $xml2 = xmlrpc_encode(array('a','b'));
    $simplexml2 = simplexml_load_string($xml2);
    print_r($xml2);
    print_r($simplexml2);
    ?>
    
    0 讨论(0)
  • 2020-11-21 07:10

    // 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);
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题