Sunday, March 13, 2011

PHP - DOMDocument For XML

To get a value of a specified tag, use

To initialize, type:
$dom = new DOMDocument();
$dom->loadXML($data); // or using $dom->load('file.xml');

To create element, use:
$city = $dom->createElement('city', 'One Bay 21th, London');

Look the real code below:

$data = '<?xml version="1.0" ?>';
$data .= '<data>';
$data .= '<name>Lady Gaga</name>';
$data .= '<city>New York</city>';
$data .= '<age>24</age>';
$data .= '</data>';

$dom = new DOMDocument();

echo $dom->getElementsByTagName('name')->item(0)->nodeValue;
echo $dom->getElementsByTagName('city')->item(0)->nodeValue;
echo $dom->getElementsByTagName('age')->item(0)->nodeValue;

// create a new node: address node
$address = $dom->createElement('address','Gaga Streets 21th');
$data = $dom->getElementsByTagName('data')->item(0);

// remove a child node: remove name node
$doc = $dom->documentElement;
$child = $doc->getElementsByTagName('name')->item(0);

// replace child nodes: replace city node with interest
$interest = $dom->createElement('interest','music');
$city = $dom->getElementsByTagName('city')->item(0);
$dom->getElementsByTagName('data')->item(0)->replaceChild($interest, $city);

// create text node: create description node
$desc = $dom->createElement('desc');
$text = $dom->createTextNode('Lady Gaga Is An Singer Of Pop');
$data = $dom->getElementsByTagName('data')->item(0);

// create attribute: album = Monster Ball Album
$album = $dom->createAttribute('album');
$value = $dom->createTextNode('Monster Ball Album');

// get the attribute: album
$desc = $dom->getElementsByTagName('desc')->item(0);
$value = $desc->getAttribute('album');
echo '<p>'.$value.'</p>';

// remove the attribute: album
$desc = $dom->getElementsByTagName('desc')->item(0);

// set the attribute: replace or add new one
$desc = $dom->getElementsByTagName('desc')->item(0);
$desc->setAttribute('album','Monster Allbum');

// set the id attribute:
$age = $dom->getElementsByTagName('age')->item(0);
$ages = $dom->getElementsByTagName('age')->item(0)->tagName;
echo $ages;

$xml = $dom->saveXML();
echo '<pre>'. htmlentities($xml).'</pre>';


No comments:

Post a Comment