Monday, December 22, 2025
HomeLanguagesPHP | DOMElement getElementsByTagName() Function

PHP | DOMElement getElementsByTagName() Function

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
 

RELATED ARTICLES

Most Popular

Dominic
32456 POSTS0 COMMENTS
Milvus
111 POSTS0 COMMENTS
Nango Kala
6823 POSTS0 COMMENTS
Nicole Veronica
11958 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12038 POSTS0 COMMENTS
Shaida Kate Naidoo
6958 POSTS0 COMMENTS
Ted Musemwa
7203 POSTS0 COMMENTS
Thapelo Manthata
6911 POSTS0 COMMENTS
Umr Jansen
6890 POSTS0 COMMENTS