daily pastebin goal
26%
SHARE
TWEET

How to convert array to SimpleXML

Mifaz Aug 17th, 2013 3,850 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. /**
  4.  * Modified http://stackoverflow.com/a/5965940/1113356, Answer
  5.  */
  6.  
  7. header('Content-Type: text/xml');
  8.  
  9. $student_info[] = array(
  10.     'id'       =>  '001',
  11.     'name'     =>  'Mifas',
  12.     'subjects' => array('English','Maths','IT')
  13. );
  14.  
  15. $student_info[] = array(
  16.     'id'    =>  '002',
  17.     'name'  =>  'Ijas',
  18.     'subjects'  => array('Science','History','Social')
  19.  
  20. );
  21.  
  22. // creating object of SimpleXMLElement
  23. $xml_student_info = new SimpleXMLElement("<?xml version=\"1.0\"?><student_info></student_info>");
  24.  
  25. // function call to convert array to xml
  26. array_to_xml($student_info,$xml_student_info);
  27.  
  28. //saving generated xml file
  29. print $xml_student_info->asXML();
  30.  
  31.  
  32. // function defination to convert array to xml
  33. function array_to_xml($student_info, &$xml_student_info) {
  34.     foreach($student_info as $key => $value) {
  35.         if(is_array($value)) {
  36.             $key = is_numeric($key) ? "item$key" : $key;
  37.             $subnode = $xml_student_info->addChild("$key");
  38.             array_to_xml($value, $subnode);
  39.         }
  40.         else {
  41.             $key = is_numeric($key) ? "item$key" : $key;
  42.             $xml_student_info->addChild("$key","$value");
  43.         }
  44.     }
  45. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top