Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

xml and php

Status
Not open for further replies.

optikalefx

Programmer
Oct 6, 2007
1
US
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.

so in this first line, how can i get the tag <pages> to use.
<?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


?>
 
Minimal correction. All comments commented out, don't know if they're still valid or not.

[tt]<?php
$doc = new DOMDocument();
$doc->preserveWhitespace = false;
$doc->load('xmltest.xml');
$xpath = new DOMXPath($doc);
$doc->formatOutput = true;
[red]//[/red]$root = $doc->createElement('pages');
[blue]$root = $doc->documentElement;[/blue]
[red]//[/red]$root = $doc->appendChild($root);
$inner = $doc->createElement('book[red]s[/red]');
$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';
?>[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top