简体   繁体   English

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

[英]Problems with creating XML with DOMDocument in PHP

The below code is fetched from php.net ( http://docs.php.net/manual/en/domdocument.savexml.php ). 以下代码是从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:\n";  
  echo $doc->saveXML() . "\n";
  echo "Saving only the title part:\n";  
  echo $doc->saveXML($title);

PHP sends a Content-type http header . PHP发送Content-type http header And by default it's text/html . 默认情况下是text/html Ie the client is supposed to interpret the response document as html. 即客户端应该将响应文档解释为html。 But you're sending an xml document (and some text and another fragment, which invalidates the output). 但是您要发送一个xml文档(以及一些文本和另一个片段,这会使输出无效)。
If you want to send an xml document tell the client so, eg via header('Content-type: text/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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM