how to append elements after root element?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
green_shores
Forum Newbie
Posts: 1
Joined: Mon Mar 21, 2011 11:26 pm

how to append elements after root element?

Post by green_shores »

:) i have this xml file coding :dubious: file name is contacts.xml)
<?xml version="1.0"?>
<contacts>

<contact>
<person>Adam</person>
<addredd>Eva street</person>
<ph>111</ph>

</contact>

<contact>
<person>Adam</person><person>John</person>
<person>Thomas street</person>
<ph>222</ph>

</contact>

<contact>
<person>Thomas</person>
<address>John street</address>
<ph>333</ph
</contact>

</contacts>


and i want to add a new "contact" element and its sub elements(person,address,ph)with their text values to this xml file using php,lets say that i start with this:
<?php

$xml = new DomDocument();
$xml->preserveWhitespace = false;
$xml->load('contacts.xml');
what is next=>?
give me exact code for answer
vishal_arora
Forum Newbie
Posts: 8
Joined: Thu Mar 24, 2011 5:08 am

Re: how to append elements after root element?

Post by vishal_arora »

<?php

include 'example.php';

$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');

$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');

$characters = $movie->addChild('characters');
$character = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');

$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');

echo $sxe->asXML();

?>

Use something like this to add new child node in xml
Post Reply