How to convert array to SimpleXML

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

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

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

    I wanted a code that will take all the elements inside an array and treat them as attributes, and all arrays as sub elements.

    So for something like

    array (
    'row1' => array ('head_element' =>array("prop1"=>"some value","prop2"=>array("empty"))),
    "row2"=> array ("stack"=>"overflow","overflow"=>"overflow")
    );
    

    I would get something like this

    <?xml version="1.0" encoding="utf-8"?>
    <someRoot>
      <row1>
        <head_element prop1="some value">
          <prop2 0="empty"/>
        </head_element>
      </row1>
      <row2 stack="overflow" overflow="stack"/>
     </someRoot>
    

    To achive this the code is below, but be very careful, it is recursive and may actually cause a stackoverflow :)

    function addElements(&$xml,$array)
    {
    $params=array();
    foreach($array as $k=>$v)
    {
        if(is_array($v))
            addElements($xml->addChild($k), $v);
        else $xml->addAttribute($k,$v);
    }
    
    }
    function xml_encode($array)
    {
    if(!is_array($array))
        trigger_error("Type missmatch xml_encode",E_USER_ERROR);
    $xml=new SimpleXMLElement('<?xml version=\'1.0\' encoding=\'utf-8\'?><'.key($array).'/>');
    addElements($xml,$array[key($array)]);
    return $xml->asXML();
    } 
    

    You may want to add checks for length of the array so that some element get set inside the data part and not as an attribute.

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

    a short one:

    <?php
    
    $test_array = array (
      'bla' => 'blub',
      'foo' => 'bar',
      'another_array' => array (
        'stack' => 'overflow',
      ),
    );
    $xml = new SimpleXMLElement('<root/>');
    array_walk_recursive($test_array, array ($xml, 'addChild'));
    print $xml->asXML();
    

    results in

    <?xml version="1.0"?>
    <root>
      <blub>bla</blub>
      <bar>foo</bar>
      <overflow>stack</overflow>
    </root>
    

    keys and values are swapped - you could fix that with array_flip() before the array_walk. array_walk_recursive requires PHP 5. you could use array_walk instead, but you won't get 'stack' => 'overflow' in the xml then.

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

    The answers provided here only convert array to XML with nodes, you are not able to set attributes. I have written a php function that allows you to convert an array to php and also set attributes for particular nodes in the xml. The downside here is you have to construct an array in a particular way with few conventions (only if you want to use attributes)

    The following example will allow you to set attributes in XML too.

    The source can be found here: 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>
    */
    ?>
    
    0 讨论(0)
  • 2020-11-21 07:23
    <?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();
    
    0 讨论(0)
  • 2020-11-21 07:23

    I found this solution similar to the original problem

    <?php
    
    $test_array = array (
      'bla' => 'blub',
      'foo' => 'bar',
      'another_array' => array (
        'stack' => 'overflow',
      ),
    );
    
    class NoSimpleXMLElement extends SimpleXMLElement {
     public function addChild($name,$value) {
      parent::addChild($value,$name);
     }
    }
    $xml = new NoSimpleXMLElement('<root/>');
    array_walk_recursive($test_array, array ($xml, 'addChild'));
    print $xml->asXML();
    
    0 讨论(0)
  • 2020-11-21 07:23

    other solution:

    $marray=array(....);
    $options = array(
                    "encoding" => "UTF-8",
                    "output_type" => "xml", 
                    "version" => "simple",
                    "escaping" => array("non-ascii, on-print, markup")
                    );
    $xmlres = xmlrpc_encode_request('root', $marray, $options);
    print($xmlres);
    
    0 讨论(0)
提交回复
热议问题