在PHP中使用DOMDocument创建XML的问题

The below code is fetched from php.net (http://docs.php.net/manual/en/domdocument.savexml.php). My problem is - it doesn't work. My only output from this is: "Saving all the document: Saving only the title part:". What am I missing here?

$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 "Saving all the document:
";  
  echo $doc->saveXML() . "
";
  echo "Saving only the title part:
";  
  echo $doc->saveXML($title);

PHP sends a Content-type http header. And by default it's text/html. I.e. the client is supposed to interpret the response document as html. But you're sending an xml document (and some text and another fragment, which invalidates the output).
If you want to send an xml document tell the client so, e.g. via header('Content-type: text/xml')

$doc = new DOMDocument('1.0');
$doc->formatOutput = true;

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

if (headers_sent() ) {
  echo 'oh oh, something wnet wrong';
}
else {
  header('Content-type: text/xml; charset=utf-8');
  echo $doc->saveXML();
}