2010-05-01 34 views
0

下面的代码是从php.net(http://docs.php.net/manual/en/domdocument.savexml.php)中提取的。我的问题是 - 它不起作用。我唯一的输出是:“保存所有文件:仅保存标题部分:”。我在这里错过了什么?在PHP中使用DOMDocument创建XML的问题

$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:\n"; 
    echo $doc->saveXML() . "\n"; 
    echo "Saving only the title part:\n"; 
    echo $doc->saveXML($title); 
+0

是否要将xml文档发送到客户端?或者你想发送一个包含“显示”一个或多个xml文档/片段的源代码的html文档吗? – VolkerK 2010-05-01 13:21:24

回答

0

PHP发送Content-type http header。并且默认情况下它是text/html。即客户端应该将响应文档解释为html。但是你正在发送一个xml文档(以及一些文本和另一个片段,这会导致输出无效)。
如果你想发送一个xml文档告诉客户端,例如通过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(); 
}