DOMDocument::getElementById

(PHP 5, PHP 7)

DOMDocument::getElementByIdSearches for an element with a certain id

说明

public DOMDocument::getElementById ( string $elementId ) : DOMElement

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

以下范例使用了 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="http://www.w3.org/1999/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>
    <xhtml:blurb><![CDATA[
<p><em>PHP Basics</em> provides an introduction to PHP.</p>
]]></xhtml:blurb>
  </book>
  <book id="php-advanced">
    <title>PHP Advanced Programming</title>
    <author email="jon.doe@advanced.php">Jon Doe</author>
  </book>
</books>
<?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 'php-basics' is: " $doc->getElementById('php-basics')->tagName "\n";

?>

以上例程会输出:

The element whose id is 'php-basics' is: book 

参见