Wednesday, September 25, 2024
Google search engine
HomeLanguagesPHP | XMLReader getAttribute() Function

PHP | XMLReader getAttribute() Function

The XMLReader::getAttribute() function is an inbuilt function in PHP which is used to get the value of a named attribute.

Syntax:

string XMLReader::getAttribute( string $name )

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

Return Value: This function returns the value of the attribute, or NULL if no attribute with the given name is found or not positioned on an element node.

Below examples illustrate the XMLReader::getAttribute() function in PHP:

Example 1:

data.xml




<?xml version="1.0" encoding="utf-8"?>
<body>
    <h1> Hello </h1>
</body>


index.php




<?php
  
// Create a new XMLReader instance
$XMLReader = new XMLReader();
  
// Load the XML file
$XMLReader->open('data.xml');
  
// Iterate through the XML
while ($XMLReader->read()) {
    if ($XMLReader->nodeType == XMLREADER::ELEMENT) {
        // Get the value of attribute with name id
        $value = $XMLReader->getAttribute('id');
  
        // Output the value to browser
        echo $value;
    }
}
?>


Output:

// Empty string because there is no attributes with name id

Program 2:
data.xml




<?xml version="1.0" encoding="utf-8"?>
<body>
    <h1 id="neveropen"> Hello </h1>
    <h2 id="my_id"> World </h2>
</body>


index.php




<?php
  
// Create a new XMLReader instance
$XMLReader = new XMLReader();
  
// Load the XML file
$XMLReader->open('data.xml');
  
// Iterate through the XML
while ($XMLReader->read()) {
    if ($XMLReader->nodeType == XMLREADER::ELEMENT) {
  
        // Get the value of attribute with name id
        $value = $XMLReader->getAttribute('id');
  
        // Output the value to browser
        echo $value . "<br>";
    }
}
?>


Output:

neveropen
my_id

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

RELATED ARTICLES

Most Popular

Recent Comments