Advertisement
abhi_madhani

Convert PHP array to xml

Jun 7th, 2014
668
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.08 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4.  * Modified v2 http://stackoverflow.com/a/5965940/1113356, Answer
  5.  */
  6.  
  7. header('Content-Type: text/xml');
  8.  
  9. $student_info = array(
  10.     0 => array(
  11.         'id'       =>  '001',
  12.         'name'     =>  'Mifas',
  13.         'subjects' => array('English','Maths','IT')
  14.     ),
  15.     1 => 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. array_to_xml($student_info,$xml_student_info);          // function call to convert array to xml
  25. print $xml_student_info->asXML();               //saving generated xml file
  26.  
  27.  
  28. // function defination to convert array to xml
  29. function array_to_xml($student_info, &$xml_student_info) {
  30.     foreach($student_info as $key => $value) {
  31.     $key = is_numeric($key) ? "item$key" : $key;
  32.         (is_array($value))     
  33.         ? array_to_xml($value, $xml_student_info->addChild("$key"))
  34.         : $xml_student_info->addChild("$key","$value");
  35.     }
  36. }
  37.  
  38. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement