2010-05-01 38 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(); 
}