array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'ja', ), 'this' => array ( 0 => 'domdocument.getelementbyid.php', 1 => 'DOMDocument::getElementById', ), 'up' => array ( 0 => 'class.domdocument.php', 1 => 'DOMDocument', ), 'prev' => array ( 0 => 'domdocument.createtextnode.php', 1 => 'DOMDocument::createTextNode', ), 'next' => array ( 0 => 'domdocument.getelementsbytagname.php', 1 => 'DOMDocument::getElementsByTagName', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'ja', 'path' => 'reference/dom/domdocument/getelementbyid.xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 5, PHP 7, PHP 8)
DOMDocument::getElementById — id に対応する要素を検索する
この関数は、 DOMDocument::getElementsByTagName と同じですが、指定した ID から要素を検索する点が違います。
この関数を動作させるには、何らかの ID 属性を DOMElement::setIdAttribute で設定するか、あるいは 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;
// ID を参照する前に、ドキュメントを検証する必要があります
$doc->validateOnParse = true;
$doc->Load('book.xml');
echo "ID が 'php-basics' の要素は " . $doc->getElementById('php-basics')->tagName . " です。\n";
?>
上の例の出力は以下となります。
ID が 'php-basics' の要素は book です。