The DOMElement::getElementsByTagName() function is an inbuilt function in PHP which is used to get the elements by tagname.
Syntax:
DOMNodeList DOMElement::getElementsByTagName( string $name )
Parameters: This function accepts a single parameter $name which holds the tag name or use * for getting all the tags.
Return Value: This function returns a DOMNodeList value containing all descendant elements with a given tag name, in the order in which they are encountered in a preorder traversal of this element tree.
Below examples illustrate the DOMElement::getElementsByTagName() function in PHP:
Example 1:
PHP
<?php
$dom = new DOMDocument();
$dom ->loadXML("<?xml version=\"1.0\"?>
<root>
<body>
<div>
<h1 style=\"color:red;\"> Hello, this is my red heading. </h1>
<h1 style=\"color:green;\"> Hello, this is my green heading. </h1>
<h1 style=\"color:blue;\"> Hello, this is my blue heading. </h1>
</div>
</body>
</root>");
$nodeList = $dom ->getElementsByTagName( 'h1' );
foreach ( $nodeList as $node ) {
echo $node ->getAttribute( 'style' ) . '<br>' ;
}
?>
|
Output:
color:red;
color:green;
color:blue;
Example 2:
PHP
<?php
$dom = new DOMDocument();
$dom ->loadXML("<?xml version=\"1.0\"?>
<root>
<body>
<div>
<p> Hello, this is my first paragraph. </p>
<p> Hello, this is my second paragraph. </p>
<p> Hello, this is my third paragraph. </p>
</div>
</body>
</root>");
$nodeList = $dom ->getElementsByTagName( 'p' );
foreach ( $nodeList as $node ) {
echo $node ->textContent . '<br>' ;
}
?>
|
Output:
Hello, this is my first paragraph.
Hello, this is my second paragraph.
Hello, this is my third paragraph.
Reference: https://www.php.net/manual/en/domelement.getelementsbytagname.php