Open In App

PHP | DOMElement getElementsByTagName() Function

Last Updated : 14 Sep, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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
 
// Create a new DOMDocument
$dom = new DOMDocument();
 
// Load the XML
$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>");
 
// Save the XML
$nodeList = $dom->getElementsByTagName('h1');
foreach ($nodeList as $node) {
    // Get the attribute value of style
    echo $node->getAttribute('style') . '<br>';
}
 
?>


Output: 

color:red;
color:green;
color:blue;

Example 2:  

PHP




<?php
 
// Create a new DOMDocument
$dom = new DOMDocument();
 
// Load the XML
$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>");
 
// Get the element by tagname
$nodeList = $dom->getElementsByTagName('p');
 
foreach ($nodeList as $node) {
    // Get the textContent
    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
 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads