DOMDocument::getElementById()函数是PHP中的内置函数,用于搜索具有特定ID的元素。
用法:
DOMElement DOMDocument::getElementById( string $elementId )
参数:此函数接受单个参数$elementId,该参数包含要搜索的id。
返回值:如果找不到该元素,则此函数返回DOMElement或NULL。
下面给出的程序说明了PHP中的DOMDocument::getElementById()函数:
程序1:在此程序中,我们将获得具有特定ID的元素的标记名。
// Create a new DOM Document
$dom = new DOMDocument('1.0', 'iso-8859-1');
// Enable validate on parse
$dom->validateOnParse = true;
// Create a div element
$element = $dom->appendChild(new DOMElement('div'));
// Create a id attribute to div
$attr = $element->setAttributeNode(
new DOMAttr('id', 'my_id'));
// Set that attribute as id
$element->setIDAttribute('id', true);
// Get the tag name
$tagname = $dom->getElementById('my_id')->tagName;
echo $tagname;
?>
输出:
div // Because id 'my_id' is applied to div tag.
程序2:在此程序中,我们将获取具有特定ID的元素的内容。
// Create a new DOM Document
$dom = new DOMDocument('1.0', 'iso-8859-1');
// Enable validate on parse
$dom->validateOnParse = true;
// Create a div element
$element = $dom->appendChild(new DOMElement('div',
'Hey, this is the text content of the div element.'));
// Create a id attribute to div
$attr = $element->setAttributeNode(
new DOMAttr('id', 'my_id'));
// Set that attribute as id
$element->setIDAttribute('id', true);
// Get the tag content
$tagcontent = $dom->getElementById('my_id')->textContent;
echo $tagcontent;
?>
输出:
Hey, this is the text content of the div element.