Sunday 24 February 2013

Add attributes to SimpleXML in PHP


We have already seen how to create basic XML and Nested XML using SimpleXML. Today we are going to see how to add attributes to simpleXML Element using addAttribute().

This addAttribute() accepts 3 Parameters:

1) Name : The name of the attribute to add.
2) Value : The value of the attribute.
3) Namespace: If specified, the namespace to which the attribute belongs.

And it doesn't return any values.

We will see, how to add type attribute to user element as shown below

<?xml version="1.0" encoding="UTF-8"?>
<users>
<user type="single">
<name id="100">suresh</name>
<user>
</users

First, we will create simpleXML Object with root element (users) using SimpleXMLElement().
Then using addchild(), we will add child element (user)  to root element (users), this method will return reference of child element added.

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

We also need to add another child element 'name' to 'user' element.

<?php
$name = $user->addChild('name','suresh');
?>

Now $user will contain reference of child element 'user' and $name will contain reference of child element 'name'.

We will add both type and id attributes to both child elements (user and name) using addAttribute().

<?php
$user->addAttribute('type','single');
$name->addAttribute('id','100');
?>

Here is the combined code for adding attributes

<?php
$users = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><users/>');
$user = $users->addChild('user');
$name = $user->addChild('name','suresh');
$user->addAttribute('type','single');
$name->addAttribute('id','100');
header('Content-Type: text/xml');
echo $users->asXML();
?>

Hope, you enjoyed this Post.

No comments:

Post a Comment