以下代码是从php.net(http://docs.php.net/manual/en/domdocument.savexml.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 "Saving all the document:\n";
echo $doc->saveXML() . "\n";
echo "Saving only the title part:\n";
echo $doc->saveXML($title);
答案 0 :(得分: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();
}