我无法从null更改DOMDocument
parentNode
。我尝试过同时使用appendChild
和replaceChild
,但没有运气。
我在哪里错了?
error_reporting(E_ALL);
function xml_encode($mixed, $DOMDocument=null) {
if (is_null($DOMDocument)) {
$DOMDocument =new DOMDocument;
$DOMDocument->formatOutput = true;
xml_encode($mixed, $DOMDocument);
echo $DOMDocument->saveXML();
} else {
if (is_array($mixed)) {
$node = $DOMDocument->createElement('urlset', 'hello');
$DOMDocument->parentNode->appendChild($node);
}
}
}
$data = array();
for ($x = 0; $x <= 10; $x++) {
$data['urlset'][] = array(
'loc' => 'http://www.example.com/user',
'lastmod' => 'YYYY-MM-DD',
'changefreq' => 'monthly',
'priority' => 0.5
);
}
header('Content-Type: application/xml');
echo xml_encode($data);
?>
答案 0 :(得分:3)
由于文档没有父节点,您需要将根节点直接附加到文档,如下所示:
$DOMDocument->appendChild($node);
自DOMDocument
扩展DOMNode
以来,这是有效的。
error_reporting(E_ALL);
function xml_encode($mixed, &$DOMDocument=null) {
if (is_null($DOMDocument)) {
$DOMDocument =new DOMDocument;
$DOMDocument->formatOutput = true;
xml_encode($mixed, $DOMDocument);
return $DOMDocument->saveXML();
} else {
if (is_array($mixed)) {
$node = $DOMDocument->createElement('urlset', 'hello');
$DOMDocument->appendChild($node);
}
}
}
$data = array();
for ($x = 0; $x <= 10; $x++) {
$data['urlset'][] = array(
'loc' => 'http://www.example.com/user',
'lastmod' => 'YYYY-MM-DD',
'changefreq' => 'monthly',
'priority' => 0.5
);
}
header('Content-Type: application/xml');
echo xml_encode($data);
顺便说一句,如果您只想序列化一个XML文件,DOM
会有点开销。我会使用模板引擎,这意味着将其作为纯文本处理。
答案 1 :(得分:1)
这应该有效,当你创建一个新的DOMDocument时,你还没有root元素,所以你可以创建它并将它添加到文档中
//You could add this to the top of xml_encode
if($DOMDocument->parentNode === null) {
$root = $DOMDocument->createElement('root');
$root = $DOMDocument->appendChild($root);
}
//Your script working:
<?php
error_reporting(E_ALL);
function xml_encode($mixed, $DOMDocument=null) {
if (is_null($DOMDocument)) {
$DOMDocument =new DOMDocument();
$DOMDocument->formatOutput = true;
//add here, but note that in the "else" it isn't sure if the DOMDocument has a root element
$root = $DOMDocument->createElement('root');
$root = $DOMDocument->appendChild($root);
xml_encode($mixed, $root);
echo $DOMDocument->saveXML();
} else {
if (is_array($mixed)) {
$node = $DOMDocument->createElement('urlset', 'hello');
$DOMDocument->parentNode->appendChild($node);
}
}
}
我不确定你为什么需要parentNode?你可以做$DOMDocument->appendChild();