Friday, December 12, 2025
HomeLanguagesPHP | DOMElement getAttribute() Function

PHP | DOMElement getAttribute() Function

The DOMElement::getAttribute() function is an inbuilt function in PHP which is used to get the value of the attribute with name for the current node.

Syntax:

string DOMElement::getAttribute( string $name )

Parameters: This function accepts a single parameter $name which holds the name of the attribute.

Return Value: This function returns an string value containing the attribute value.

Below given programs illustrate the DOMElement::getAttribute() function in PHP:

Program 1:




<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
  
// Load the XML
$dom->loadXML("<?xml version=\"1.0\"?>
<body>
    <strong attr=\"value\"> 22 </strong>
</body>");
  
// Get the strong element
$element = $dom->getElementsByTagName('strong');
  
// Get the attribute
$value = $element[0]->getAttribute('attr');
echo $value;
?>


Output:

value

Program 2:




<?php
  
// Create a new DOMDocument
$dom = new DOMDocument();
  
// Load the XML
$dom->loadXML("<?xml version=\"1.0\"?>
<body>
    <div id=\"div1\"> DIV 1 </div>
    <div id=\"div2\"> DIV 2 </div>
    <div id=\"div3\"> DIV 3 </div>
</body>");
  
// Get all the div elements
$elements = $dom->getElementsByTagName('div');
  
// Get the id value of each element
echo "All the id values of divs are: <br>";
foreach ($elements as $element) {
    echo $element->getAttribute('id') . "<br>";
}
?>


Output:

All the id values of divs are:
div1
div2
div3

Reference: https://www.php.net/manual/en/domelement.getattribute.php

RELATED ARTICLES

Most Popular

Dominic
32445 POSTS0 COMMENTS
Milvus
105 POSTS0 COMMENTS
Nango Kala
6813 POSTS0 COMMENTS
Nicole Veronica
11952 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12029 POSTS0 COMMENTS
Shaida Kate Naidoo
6949 POSTS0 COMMENTS
Ted Musemwa
7199 POSTS0 COMMENTS
Thapelo Manthata
6894 POSTS0 COMMENTS
Umr Jansen
6881 POSTS0 COMMENTS