简体   繁体   中英

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"));

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.

id is only an id attribute if defined by the DTD/XSD or API. The only predefined id attribute in XML is xml:id ( {http://www.w3.org/XML/1998/namespace}id ).

You can use Xpath to fetch an node by its attribute value. It does not need to by an id attribute for that:

$xml = <<<'XML'
<?xml version="1.0"?>
<root>
  <element id="1"/>
  <element id="2"/>
  <element id="3"/>
</root>
XML;

$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);

var_dump(
  $xpath->evaluate('//*[@id=2]')->item(0)->getAttribute('id')
);

Output:

string(1) "2"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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