How to convert array to SimpleXML

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

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

30条回答
  •  我在风中等你
    2020-11-21 07:23

    a short one:

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

    results in

    
    
      bla
      foo
      stack
    
    

    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.

提交回复
热议问题