DOMDocument::getElementById
DOMDocument::getElementById
(PHP 5, PHP 7)
DOMDocument :: getElementById - 搜索具有特定ID的元素
描述
public DOMElement DOMDocument::getElementById ( string $elementId )
该函数与DOMDocument :: getElementsByTagName类似,但是搜索具有给定id的元素。
为了使此功能起作用,您需要使用DOMElement :: setIdAttribute设置一些ID属性,或者将定义属性的DTD设置为ID类型。在后一种情况下,在使用此函数之前,您需要使用DOMDocument :: validate或DOMDocument :: $ validateOnParse验证文档。
参数
elementId
元素的唯一id值。
返回值
返回DOMElement或者NULL
找不到元素。
例子
示例#1 DOMDocument :: getElementById()示例
以下示例使用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