Advertisement
Mifaz

How to convert array to SimpleXML

Aug 17th, 2013
4,626
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.19 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement