Lambda function to create XML from Array


/ Published in: PHP
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.