Thursday 21 February 2013

create XML using SimpleXML in PHP


We will see how to create XML using simpleXML. we will creating the below XML

<?xml version="1.0" encoding="UTF-8"?>
<users>
<user>
 <id>2011</id>
 <name>A Suresh</name>
 <age>29</age>
 <role>Senior Developer</role>
</user>
</users>

First, Create simpleXML object with root element (users) using SimpleXMLElement()

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

then add child element (user) to the root element (users) using addChild(), this will return the reference of the child element added.

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

now $user will contain reference of child element added (user), we will add other child elements with values to user.

<?php
$user->addChild('id',2011);
$user->addChild('name','A Suresh');
$user->addChild('age',29);
$user->addChild('role','Senior Developer');
?>

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 XML using SimpleXML

<?php
$users = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><users/>');
$user = $users->addChild('user');
$user->addChild('id',2011);
$user->addChild('name','A Suresh');
$user->addChild('age',29);
$user->addChild('role','Senior Developer');
header('Content-Type: text/xml');
echo $users->asXML();
?>

I hope you enjoyed this Post.

No comments:

Post a Comment