DOMDocument
在线手册:中文 英文
PHP手册

DOMDocument::getElementById

(PHP 5)

DOMDocument::getElementByIdSearches for an element with a certain id

说明

DOMElement DOMDocument::getElementById ( string $elementId )

This function is similar to DOMDocument::getElementsByTagName but searches for an element with a given id.

For this function to work, you will need either to set some ID attributes with DOMElement::setIdAttribute or a DTD which defines an attribute to be of type ID. In the later case, you will need to validate your document with DOMDocument::validate or DOMDocument::$validateOnParse before using this function.

参数

elementId

The unique id value for an element.

返回值

Returns the DOMElement or NULL if the element is not found.

范例

Example #1 DOMDocument::getElementById() Example

<?php

$doc 
= new DomDocument;

// We need to validate our document before refering to the id
$doc->validateOnParse true;
$doc->Load('book.xml');

echo 
"The element whose id is books is: " $doc->getElementById('books')->tagName "\n";

?>

以上例程会输出:

The element whose id is books is: chapter

参见


DOMDocument
在线手册:中文 英文
PHP手册
PHP手册 - N: Searches for an element with a certain id

用户评论:

cristian dot gohl at live dot com (22-Mar-2012 03:24)

Hello, I imported html and it worked ok.

$test = $dom->getElementById('ID');
 return $testes->nodeValue; // OK, span tag.

This html have js script.

Eg. var IDID = {..}

I tried get this element, but only return null.

ed at edgiardina dot com (13-Oct-2010 07:41)

Please note that if your HTML does not contain a doctype declaration, then getElementById will always return null.

paradox_haze at live dot de (02-Mar-2010 06:53)

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:

<?php
function getElementById($id)
{
   
$xpath = new DOMXPath($this->domDocument);
    return
$xpath->query("//*[@id='$id']")->item(0);
}
?>

gurmukh24 at gmail dot com (04-May-2009 05:40)

See example how multiple attributes and childs are parsed using php in a perfect way. coder : gurmukh singh Bhatti
<?php
$xml
=<<<EOT
<?xml version="1.0"?>
<root>
<section name="Section1">
  <category id="Category1" name="google">
   <arti name="article1">
   <p>any html code here</p>
   <b>my name is so so</b>
    </arti>
   <arti name="article2">value2</arti>
   <arti name="article3">value3</arti>
   <arti name="article4">value4</arti>
  </category>
    <category id="Category2" name="yahoo">
   <arti name="articleSection2">Test value</arti>
  </category>
</section>
<section name="Section2">
  <category id="category1_of_section2" name="msn">
   <arti name="article2">value1</arti>
   <arti name="article3">value2</arti>
  </category>
    <category id="Category2_of_section2" name="webcare">
    <arti name="param3">value4</arti>
   </category>
</section>
</root>
EOT;

$dom = new DomDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($xml);
$params = $dom->getElementsByTagName('section'); // Find Sections
$k=0;
foreach (
$params as $param) //go to each section 1 by 1
{
         echo
"Section Attribute :-> ".$params->item($k)->getAttribute('name')."<br>";   //get section attribute          
        
$params2 = $params->item($k)->getElementsByTagName('category'); //digg categories with in Section
     
$i=0; // values is used to iterate categories
       
foreach ($params2 as $p) {
           echo
"&nbsp;&nbsp;- Category Attribute Name :-> ".$params2->item($i)->getAttribute('name')."<br>"; //get Category attributes
           
$params3 = $params2->item($i)->getElementsByTagName('arti'); //dig Arti into Categories
                
$j=0;//values used to interate Arti
                    
foreach ($params3 as $p2)
                   {
                    echo
"&nbsp;&nbsp;&nbsp;- Article Attribute Name : ".$params3->item($j)->getAttribute('name').""; //get arti atributes
echo "&nbsp;&nbsp; Value : ".$params3->item($j)->nodeValue."<br>"; //get Node value ;
                             
$j++; 
                   }            
        
$i++;
      }
$k++;  
        
}
?>

output :
 Section Attribute :-> Section1
  - Category Attribute Name :-> google
            - Article Attribute Name : article1   Value : any html code heremy name is so so
            - Article Attribute Name : article2   Value : value2
            - Article Attribute Name : article3   Value : value3
            - Article Attribute Name : article4   Value : value4
  - Category Attribute Name :-> yahoo
            - Article Attribute Name : articleSection2   Value : Test value
Section Attribute :-> Section2
  - Category Attribute Name :-> msn
            - Article Attribute Name : article2   Value : value1
            - Article Attribute Name : article3   Value : value2
  - Category Attribute Name :-> webcare
            - Article Attribute Name : param3   Value : value4

carl2088 at gmail dot com (11-Apr-2009 08:41)

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.

<?php

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

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

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

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

   
$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->save("./_data/test.xml");
   
   
$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!
       
   
?>

guillaume dot crico at gmail dot com (01-Oct-2008 03:55)

You don't want to use "xml:id" ?
Here is the relaxNG trick (with a generic schema):
(tested with libxml 2.6.26)

<?php
$doc
= new DOMDocument();
$doc->load(...);

$rng = '
<grammar xmlns="http://relaxng.org/ns/structure/1.0" datatypeLibrary="http://www.w3.org/2001/XMLSchema-datatypes">
    <start>
        <element>
            <anyName/>
            <ref name="anythingID"/>
        </element>
    </start>
    <define name="anythingID">
        <zeroOrMore>
            <choice>
                <element>
                    <anyName/>
                    <ref name="anythingID"/>
                </element>
                <attribute name="id">
                    <data type="ID"/>
                </attribute>
                <zeroOrMore>
                    <attribute><anyName/></attribute>
                </zeroOrMore>
                <text/>
            </choice>
        </zeroOrMore>
    </define>
</grammar>
'
;

$doc->relaxNGValidateSource($rng);
var_dump($doc->getElementById('id1'));
?>


Note that ID values must be valid ones :
  - integers do no work!
  - @see http://www.w3.org/TR/REC-xml/#id
  - => (Letter | '_' | ':') ( Letter | Digit | '.' | '-' | '_' | ':' | CombiningChar | Extender  )*

simon at somewhere dot com (30-Jan-2007 04:07)

SAVE YOURSELF A MAJOR HEADACHE AND A LOT OF SEARCHING THROUGH DOCUMENTATION -

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......

jonbarnett at gmail dot com (01-Nov-2006 04: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']"

Tangui dot Le-Pense at laposte dot net (08-Apr-2006 02:00)

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.
http://www.w3.org/TR/xml-id/

(20-Dec-2005 03:04)

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
Example:

  $dom = new DomDocument();
  $dom->load("users.xml");
  $dom->schemaValidate("users.xsd");

  $curruser = $dom->getElementById($user->name);

bart at mediawave dot nl (11-Sep-2005 12:46)

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.