Last updated: December 2, 2026.
If an XML document identifies records with an unprefixed attribute such as key, mark it as an ID with setIdAttribute() before doing an ID lookup.
<?php
$xml = Dom\XMLDocument::createFromString(
'<catalog><entry key="alpha">Notebook</entry></catalog>'
);
$entry = $xml->getElementsByTagName('entry')->item(0);
$entry->setIdAttribute('key', true);
$found = $xml->getElementById('alpha');
echo $found?->textContent, PHP_EOL; // NotebookRegister the attribute on the element that owns it
The example uses the modern DOM API available from PHP 8.4. The attribute already exists, and the call registers it on the specific element. It does not create a new attribute or declare that all other key attributes are IDs. If the document contains multiple records, register their keys as needed and check they are unique.
For an attribute without a prefix, use its name directly. A default namespace on an XML element does not put its unprefixed attributes in that namespace. For a genuinely namespaced attribute, use the namespace URI and local name with the namespace-aware method. A prefix on the wire can change without changing the namespace URI.
Check whether the document already declares IDs
Some documents already identify attributes as IDs through their document type. For application-defined XML with plain attributes, explicit registration is useful when lookup repeatedly runs against the same in-memory DOM. For a single lookup, walking the intended elements and comparing their attribute values is also straightforward.
Verify that a known ID returns the expected element and that a missing ID returns null. Inspect attribute presence before registering it when a record may omit its key. Keep the lookup separate from XML parsing policy. The sample uses fixed XML, and processing external XML requires choosing parser settings appropriate to that input.