PHP | XMLReader getAttributeNs() Function

The XMLReader::getAttributeNs() function is an inbuilt function in PHP which is used to get the value of an attribute by name and namespace URI or an empty string if attribute does not exist or not positioned on an element node.
Syntax:
string XMLReader::getAttributeNs( string $localName,
string $namespaceURI )
Parameters: This function accept two parameters as mentioned above and described below:
- $localName: It specifies the local name.
- $namespaceURI: It specifies the namespace URI.
Return Value: This function returns the value of attribute on success or empty string on failure.
Below examples illustrate the XMLReader::getAttributeNs() function in PHP:
Example 1:
- data.xml
<?xmlversion="1.0"encoding="utf-8"?><divxmlns:x="zambiatek">Â Â Â Â<x:h1x:attrib="value">Â Â Â Â Â ÂNamespaced TextÂÂ Â Â Â</x:h1></div> - index.php
<?phpÂÂ// Create a new XMLReader instance$XMLReader=newXMLReader();ÂÂ// Load the XML file$XMLReader->open('data.xml');ÂÂ// Move to next node three times$XMLReader->read();$XMLReader->read();$XMLReader->read();ÂÂ// Get the value of attribute but// give a wrong namespace here$value=$XMLReader->getAttributeNs(Â Â Â Â"attrib","wrong_namespace");ÂÂ// Output the value to browserecho$value."<br>";ÂÂ?> - Output:
// Empty string because namespace name doesn't match
Example 2:
- data.xml
<?xmlversion="1.0"encoding="utf-8"?><divxmlns:x="my_namespace">Â Â Â Â<x:h1x:attrib="value">ÂÂ Â Â Â Â ÂNamespaced TextÂÂ Â Â Â</x:h1></div> - index.php
<?phpÂÂ// Create a new XMLReader instance$XMLReader=newXMLReader();ÂÂ// Load the XML file$XMLReader->open('data.xml');ÂÂ// Iterate through the XMLwhile($XMLReader->read()) {   Âif($XMLReader->nodeType == XMLREADER::ELEMENT) {       Â// Get the value of attribute with name "attrib"       Â// and namespace "my_namespace"       Â$value=$XMLReader->              ÂgetAttributeNs("attrib","my_namespace");       Â// Output the value to browser       Âecho$value."<br>";   Â}}?> - Output:
value
Reference: https://www.php.net/manual/en/xmlreader.getattributens.php
Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, zambiatek Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!



