(PHP 5)

DOMDocument::getElementById Ищет элемент с заданным id


public DOMElement DOMDocument::getElementById ( string $elementId )

Эта функция является аналогом DOMDocument::getElementsByTagName, но ищет элемент по его id.

Для работы этой функции необходимо либо задать ID атрибуты элементов посредством DOMElement::setIdAttribute, либо понадобится DTD, которая определяет атрибут как имеющий тип ID. В последнем случае перед использованием этой функции потребуется проверять документ на действительность посредством DOMDocument::validate или DOMDocument::$validateOnParse.

Список параметров


Уникальный id элемента.

Возвращаемые значения

Возвращает объект DOMElement либо NULL, если элемент не найден.


Пример #1 DOMDocument::getElementById() Example

Следующие примеры используют файл book.xml, который содержит следующие данные:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books [
  <!ELEMENT books   (book+)>
  <!ELEMENT book    (title, author+, xhtml:blurb?)>
  <!ELEMENT title   (#PCDATA)>
  <!ELEMENT blurb   (#PCDATA)>
  <!ELEMENT author  (#PCDATA)>
  <!ATTLIST books   xmlns        CDATA  #IMPLIED>
  <!ATTLIST books   xmlns:xhtml  CDATA  #IMPLIED>
  <!ATTLIST book    id           ID     #IMPLIED>
  <!ATTLIST author  email        CDATA  #IMPLIED>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<books xmlns="http://books.php/" xmlns:xhtml="">
  <book id="php-basics">
    <title>PHP Basics</title>
    <author email="jim.smith@basics.php">Jim Smith</author>
    <author email="jane.smith@basics.php">Jane Smith</author>
<p><em>PHP Basics</em> provides an introduction to PHP.</p>
  <book id="php-advanced">
    <title>PHP Advanced Programming</title>
    <author email="jon.doe@advanced.php">Jon Doe</author>

= new DomDocument;

// Необходимо проверить документ на действительность перед тем как 
// ссылаться на id
$doc->validateOnParse true;

"Элемент с id 'php-basics': " $doc->getElementById('php-basics')->tagName "\n";


Результат выполнения данного примера:

Элемент с id 'php-basics': book

Смотрите также


It seems getElementById works fine without setting validateOnParse to true. Which is nice since setting this to true caused some performance problems with my script.
2005-09-11 07:46:24
If you're trying to use getElementById with a xml file validated on a xsd file you must first use the schemaValidate function or getElementById will return null

  $dom = new DomDocument();

  $curruser = $dom->getElementById($user->name);
2005-12-20 09:04:59
Validating a document from a DTD so as to use getElementById is sometimes impossible (for example when the head and body elements are not included yet in a XHtml document : the validation failed).
Fortunately, xml:id is supported by this function :)
That may be useful.
2006-04-08 09:00:36
If your XML document does not have a DTD that defines the "id" attribute as an ID, then the easiest thing to do is to use XPath->query() to find an element that matches "//[@id='x']"
2006-11-01 10:36:35

Instead of using $object->setAttribute('id', 'id_name_here')
USE THIS: $object->setAttribute('xml:id', 'id_name_here')

Then, to get the node value: $domDocumentObject->getElementById('id_name_here');

The xml:id attribute should AUTOMATICALLY be defined!!

Woohoo!  That was easy......
2007-01-29 22:07:06
You don't want to use "xml:id" ?
Here is the relaxNG trick (with a generic schema):
(tested with libxml 2.6.26)

= new DOMDocument();

$rng '
<grammar xmlns="" datatypeLibrary="">
            <ref name="anythingID"/>
    <define name="anythingID">
                    <ref name="anythingID"/>
                <attribute name="id">
                    <data type="ID"/>


Note that ID values must be valid ones :
  - integers do no work! 
  - @see
  - => (Letter | '_' | ':') ( Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender  )*
2008-10-01 10:55:35
From my experience, getElementById seem to work fine without any setups if you have loaded a HTML document. But in order for getElementById to work with a simple XML document that you've "constructed", you have to set up the id with "xml:" prefix and use setIdAttribute on the element you created or it won't work. See following example, hope this will save someone's frustration. If you have loaded the xml file, then all you have to make sure is the ID has a xml: prefix for the attribute.  But if you start to append the XML document, don't forget to setIdAttribute on the id name or those elements or getElementById will return null when you try to find them. 


/* test.xml
    <?xml version="1.0" encoding="utf-8"?>
        <child xml:id="id_xxxxxx" status="partial">
            <sub_child>Some Data</sub_child>

$xmlDom = new DOMDocument('1.0''utf-8');
$xmlDom->formatOutput true;                        // we want a nice output

    // create a root
$eltRoot $xmlDom->createElement("root");

$eltChild $xmlDom->createElement("child");
// add a id attribute
$attr $xmlDom->createAttribute("xml:id");    // needs xml prefix or getElementById won't work
/// create the text node and append to the created element
$tNode $xmlDom->createTextNode("id_8120528");
$eltChild->setIdAttribute("xml:id"true);    // VERY IMPORT or getElementById won't work
    // add a id attribute
$attr $xmlDom->createAttribute("status");
/// create the text node and append to the created element
$tNode $xmlDom->createTextNode("partial");
// add a subchild
$eltSub $xmlDom->createElement("sub_child");
$tNode $xmlDom->createTextNode("Some Data");

$id null;
$id $xmlDom->getElementById("id_8120528");
assert ($id != null);
$strId $id->getAttribute("xml:id"); // bug? empty
$strStatus $id->getAttribute("status"); // this works!
assert ($id !=null);
$xmlDom->load("./_data/test.xml"); // reloading fixes the problem
$nodeRoot $xmlDom->getElementsByTagName("root");
    if (
$nodeRoot->length 0) {
$eltRoot $nodeRoot->item(0);   
assert($eltRoot != null);
$id null;
$id $xmlDom->getElementById("id_8120528");

assert ($id != null);

$strId $id->getAttribute("xml:id"); // this works now!
$strStatus $id->getAttribute("status"); // this works!
2009-04-11 03:41:49
Had some issues with getElementById() while searching for a specific element in a XHTML document.
I wrote a small function what was solving my problem:

function getElementById($id)
$xpath = new DOMXPath($this->domDocument);
2010-03-02 12:53:02
Please note that if your HTML does not contain a doctype declaration, then getElementById will always return null.
2010-10-13 14:41:03

    Поддержать сайт на родительском проекте КГБ