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:



Exampple 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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>';
}
  
?>

chevron_right


Output:

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

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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>';
}
?>

chevron_right


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




My Personal Notes arrow_drop_up

I love Open Source Culture have contributed to phpMyAdmin, LibreOffice, Ant-Design and Web is my passion

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.