Page 1 of 1

Saving a DOM tree into a string

Posted: Sun Sep 12, 2010 9:13 pm
by jdoe
Hi, I am a newbie in PHP. Now I am learning some sample using XML/DOM.

I just cut and paste the code of Example #1 Saving a DOM tree into a string
from this url: http://www.php.net/manual/en/domdocument.savexml.php

When I open the code in Chrome browser, I did not get the expected output.

My output was :
Saving all the document: Saving only the title part:

The expected output was:
Saving all the document:
<?xml version="1.0"?>
<book>
<title>This is the title</title>
</book>

Saving only the title part:
<title>This is the title</title>

Question:Could you please help to explain why I did not get the expected output?
Thanks.


The following is the code from the mentioned url:
<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

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

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

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

echo "Retrieving all the document:\n";
echo $doc->saveXML() . "\n";

echo "Retrieving only the title part:\n";
echo $doc->saveXML($title);

?>

Re: Saving a DOM tree into a string

Posted: Sun Sep 12, 2010 9:46 pm
by Jonah Bron
Incorrect. appendChild() changes the node in place, and return the node added, not the node added to. Here is the correct version.

Code: Select all

<pre><?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$title = $doc->createElement('title');
$text = $doc->createTextNode('This is the title');

$title->appendChild($text);
$root->appendChild($title);
$doc->appendChild($root);

echo "Retrieving all the document:\n";
echo $doc->saveXML() . "\n";

echo "Retrieving only the title part:\n";
echo $doc->saveXML($title);

?></pre>
I took the liberty of adding a <pre> tag around the output to preserve format.

Re: Saving a DOM tree into a string

Posted: Sun Sep 12, 2010 9:49 pm
by jdoe
Guys, I figured out the solution.
Changed the code to include:

echo "<PRE>";
echo "Retrieving all the document:\n";
echo htmlentities($doc->saveXML()) . "\n";

echo "Retrieving only the title part:\n";
echo htmlentities($doc->saveXML($title));

echo "</PRE>";

Thanks.

Re: Saving a DOM tree into a string

Posted: Sun Sep 12, 2010 9:54 pm
by jdoe
Hi Jonah Bron.
Thanks for your prompt response.
I took your code and it still wouldn't show the output. It shows only below:


Retrieving all the document:




Retrieving only the title part:

Re: Saving a DOM tree into a string

Posted: Sun Sep 12, 2010 9:57 pm
by Jonah Bron
Oh yeah, should have realized that the browser would be trying to read it as HTML. Silly me :crazy: