user1517081 user1517081 - 6 months ago 20
PHP Question

getElementById on dynamically created XML

The example speaks for itself, I expect getElementById to return the second element but NULL is given. How come?

$dom = new DOMDocument();

$root = $dom->createElement("root");

$el = $dom->createElement("element");
$el->setAttribute("id", "1");
$root->appendChild($el);

$el = $dom->createElement("element");
$el->setAttribute("id", "2");
$root->appendChild($el);

$dom->appendChild($root);

// OK
echo $dom->saveXML();

// NOT OK
var_dump($dom->getElementById("2"));

Answer

With XML the getElementById method returns elements for which a certain attribute has been defined in the DTD as having type ID and not those named id. So you would need to make sure you have a DTD declaring the type ID for the elements named element and the attribute named id if you want to be able to use that method:

$dom = new DOMDocument();
$dom->loadXML("<!DOCTYPE root [<!ATTLIST element id ID #IMPLIED>]><root/>");

$root = $dom->documentElement;

It seems that in the PHP DOM API doing

$el = $dom->createElement("element");
$el->setAttribute("id", "2");
$el->setIdAttribute("id", TRUE);

serves as an alternative to having a DTD.