php - DOMDocument cannot change parentNode
222
I cannot change theDOMDocument
parentNode
from null. I have tried using bothappendChild
andreplaceChild
, but haven't had any luck.
Where am I going wrong here?
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);
?>
Answer
Solution:
Since the document has no parent node you need to append the root node directly to the document, like this:
This works since
DOMDocument
extendsDOMNode
.Working example:
Btw, if you just want to serialize an XML file,
DOM
is a bit overhead. I would use a template engine for this, meaning handle it as plain text.Answer
Solution:
This should work, when you create a new DOMDocument you don't have a root element yet, so you can just create it and add it to the document
I'm not sure why you need the parentNode? you could do
$DOMDocument->appendChild();