Friday, 22 February 2013

Create Nested XML using SimpleXML in PHP


If you are not familiar with creating Basic XML using simpleXML. First read this Post. Today, we are going to see how to create Nested XML as shown below using SimpleXML.

<?xml version="1.0" encoding="UTF-8"?>
<users>
<user>
    <begineer>
       <courses>
          <course>Php</course>
          <course>Ajax</course>
       </courses>
     </begineer>
     <advanced>
<courses>
           <course>Java</course>
  <course>J2EE</course>
</courses>
     </advanced>
</user>
</users>

Create a new simpleXML object with root element (users) using SimpleXMLElement()

<?php
$users = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?></users>');
?>

Add child element (user) to the root element (users) using addChild(). This addChild() will return the reference of the child element added.

<?php
$user = $users->addChild('user');
?>

There are 2 child elements (begineer and advanced) present under 'user' element and these needed to be added using addChild().

<?php
$begineer = $user->addChild('begineer');
$advanced = $user->addChild('advanced');
?>

Now $begineer will contain reference of 'begineer' element and $advanced will contain reference of 'advanced' element.
We need to add 'courses' child element to both 'begineer' and 'advanced' element.

<?php
$begineercourses = $begineer->addChild('courses');
$advancedcourses = $advanced->addChild('courses');
?>

We need to add 'course' child element to both begineer and advanced courses.

<?php
$begineercourses->addChild('course','Php');
$begineercourses->addChild('course','Ajax');

$advancedcourses->addChild('course','Java');
$advancedcourses->addChild('course','J2EE');
?>

use asXML(), which will convert SimpleXML Object to well-formed XML string and output to browser.
you can use header() function with 'Content-Type:text/xml' which will tell the browser that we are going to output XML data.

<?php
header('Content-Type: text/xml');
echo $users->asXML();
?>

Following is the combined code for creating Nested XML using SimpleXML

<?php
$users = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?></users>');
$user = $users->addChild('user');
$begineer = $user->addChild('begineer');
$advanced = $user->addChild('advanced');
$begineercourses = $begineer->addChild('courses');
$advancedcourses = $advanced->addChild('courses');
$begineercourses->addChild('course','Php');
$begineercourses->addChild('course','Ajax');

$advancedcourses->addChild('course','Java');
$advancedcourses->addChild('course','J2EE');

header('Content-Type: text/xml');
echo $users->asXML();
?>

I hope you enjoyed this Post.

1 comment: