XML with PHP

admin

Administrator
Staff member
i have an xml document

<pages>
<books>
<title>words</title>
</books>
</pages>

I cant for the life of me figure out how to add a new

<books>
<title>words</title>
</books>

inside of <pages>

so far im able to create the new node and values after the </pages> which throws an error.


Here is my php file, and you can see the line of code im commenting around
I need that line to get the tag pages, and store it into $root, so that i can create a child of that.

Right now its creating pages, and thats not right because it already exists.
<?php

$doc = new DOMDocument();
$doc->preserveWhitespace = false;
$doc->load('xmltest.xml');
// we want a nice output
$xpath = new DOMXPath($doc);
$doc->formatOutput = true;


/* THIS NEEDS TO GET TAG <PAGES> AND STORE IT TO $ROOT */
$root = $doc->createElement('pages');
/* THIS NEEDS TO GET TAG <PAGES> AND STORE IT TO $ROOT */



$root = $doc->appendChild($root);

$inner = $doc->createElement('book');
$inner = $root->appendChild($inner);

$title = $doc->createElement('title');
$title = $inner->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);


echo 'Wrote: ' . $doc->save("xmltest.xml") . ' bytes'; // Wrote: 72 bytes


?>
 
Back
Top