Posted By

abrahamsustaita on 03/06/13


Tagged

php array xml


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

ringo380


Lambda function to create XML from Array


 / Published in: PHP
 

This snippet is a lambda function (anonymous function) to create an xml from an array. It uses recursiveness.

  1. <?php
  2. $toXml = function ( &$xml, $data ) use ( &$toXml ) {
  3. foreach ( $data as $key => $value ) {
  4. $xml->addChild ( $key );
  5. if ( is_array ( $value ) ) {
  6. $toXml ( $xml->$key, $value );
  7. } else {
  8. $xml->$key = $value;
  9. }
  10. }
  11. };
  12.  
  13. $data = array (
  14. "key1" => "value2",
  15. "key2" => array (
  16. "subkey1" => "subvalue1"
  17. )
  18. );
  19. $xml = new SimpleXMLElement ( "<root />" );
  20. $toXml ( $xml, $data );
  21.  
  22. echo $xml->asXML();

Report this snippet  

You need to login to post a comment.