PHP-XML New Attribute Create and Append In Existing XML File

PHP-XML New Attribute Create and Append In Existing XML File


Posted in : PHP Posted on : January 21, 2011 at 6:11 PM Comments : [ 0 ]

This section contains the detail about the XML New Attribute Create and Append In Existing XML File

PHP-XML New Attribute Create and Append In Existing XML File:

In this example, we will create a new attribute and append in the existing xml file.

Example:

<?php
$xml_doc = new DomDocument;

$xml_doc->Load('root.xml');

$child2 = $xml_doc->getElementsByTagName('child2')->item(0);

$newattribute=$xml_doc->createAttribute('name');

$child2 -> appendChild($newattribute);

$test = $xml_doc->save("root.xml");

echo "<B>New Attribute Created<B>"
?>

First of all, we have create a dom document object and load xml file in this object. After that we have used getElementByTagName("tagname") to find the element from the XML file and store it like:

<?php
$xml_doc = new DomDocument;

$xml_doc->Load('root.xml');

$child2 = $xml_doc->getElementsByTagName('child2')->item(0);

After that we have create a new attribute with name of the attribute and append it in the element and save the file.

Browser Output:

New Attribute Created

And root.xml file content is:

<?xml version="1.0"?>
<root>
<child1 chield1_attribute="chield1 attribute value">clied1 text</child1>
<child2 name="">clied2 text</child2>
</root>

Download Example Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics