PHP | DOMDocument getElementById() Function
Last Updated :
20 Feb, 2020
The DOMDocument::getElementById() function is an inbuilt function in PHP which is used to search for an element with a certain id.
Syntax:
DOMElement DOMDocument::getElementById( string $elementId )
Parameters:This function accepts a single parameter $elementId which holds the id to search for.
Return Value: This function returns the DOMElement or NULL if the element is not found.
Below given programs illustrate the DOMDocument::getElementById() function in PHP:
Program 1: In this program we will get the tagname of element with certain id.
<?php
$dom = new DOMDocument( '1.0' , 'iso-8859-1' );
$dom ->validateOnParse = true;
$element = $dom ->appendChild( new DOMElement( 'div' ));
$attr = $element ->setAttributeNode(
new DOMAttr( 'id' , 'my_id' ));
$element ->setIDAttribute( 'id' , true);
$tagname = $dom ->getElementById( 'my_id' )->tagName;
echo $tagname ;
?>
|
Output:
div // Because id 'my_id' is applied to div tag.
Program 2: In this program we will get the content of element with certain id.
<?php
$dom = new DOMDocument( '1.0' , 'iso-8859-1' );
$dom ->validateOnParse = true;
$element = $dom ->appendChild( new DOMElement( 'div' ,
'Hey, this is the text content of the div element.' ));
$attr = $element ->setAttributeNode(
new DOMAttr( 'id' , 'my_id' ));
$element ->setIDAttribute( 'id' , true);
$tagcontent = $dom ->getElementById( 'my_id' )->textContent;
echo $tagcontent ;
?>
|
Output:
Hey, this is the text content of the div element.
Reference: https://www.php.net/manual/en/domdocument.getelementbyid.php
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...