【问题标题】:Problems with creating XML with DOMDocument in PHP在 PHP 中使用 DOMDocument 创建 XML 的问题
【发布时间】:2010-05-01 12:48:05
【问题描述】:

以下代码取自 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);

【问题讨论】:

  • 您想向客户端发送一个 xml 文档吗?或者您想发送一个包含“显示”一个或多个 xml 文档/片段的源代码的 html 文档?

标签: php xml dom


【解决方案1】:

PHP 发送一个Content-type http header。默认情况下它是text/html。 IE。客户端应该将响应文档解释为 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    相关资源
    最近更新 更多