• PHP Video Tutorials

PHP SimpleXMLElement::attributes() Function



Definition and Usage

XML is a mark-up language to share the data across the web, XML is for both human read-able and machine read-able. The SimpleXMLElement class represents an XML document in PHP.

The SimpleXMLElement::attributes() function finds out the attributes along with the values in the SimpleXMLElement object and returns them.

Syntax

SimpleXMLElement::attributes([$namespace, $is_prefix]);

Parameters

Sr.No Parameter & Description
1

namespace(Optional)

This is a string value representing the namespace to which the attribute belongs.

2

Is_prefix(Optional)

This is a boolean value representing whether the specified name space is a prefix (TRUE) or an URL (FALSE).

Return Values

This function returns an object of the SimpleXMLElement class containing the attributes and it FALSE if called on an attribute.

PHP Version

This function was first introduced in PHP Version 5 and works in all the later versions.

Example

Following example demonstrates the usage of the SimpleXMLIterator::attributes() function.

<html>
   <head>
      <body>
         <?php
            $str="<?xml version='1.0' standalone='yes'?>
            <Tutorial>
               <Name type = 'programming'>JavaFX</Name>
               <Pages>535</Pages>
               <Author>Krishna</Author>
               <Version>11</Version>
            </Tutorial>";
            $xml = new SimpleXMLElement($str);
            $attr = $xml->Name->attributes();
            print_r($attr); 
         ?>      
      </body>
   </head>   
</html>

This will produce following result −

SimpleXMLElement Object ( [@attributes] => Array ( [type] => programming ) )

Example

Assume we have a xml file with the following tag −

Data.xml:

<Tutorials>

</Tutorials>

In the following example we are adding a child element with an attribute and retrieving it using the attributes() function −

<html>
   <head>      
      <body>         
         <?php
            $doc = new DOMDocument;
            $xml = simplexml_load_file("data.xml");
            
            //file to SimpleXMLElement 
            $simpleXmlElement = simplexml_import_dom($xml);
            
            //Adding the child node
            $child = $xml->addChild('Tutorial');
            $ele = $child->addChild('Name', 'OpenCV');
            $ele->addAttribute('type', 'Image Processing');			
            $child->addChild('Pages', '230');
            $child->addChild('Author', 'Maruthi');
            $child->addChild('Version', '5.5');
            $xml->asXML("output.xml");   
            $attr = $xml->Tutorial->Name->attributes();
            print_r($attr); 			
         ?>
      </body>
   </head>
</html>

This will produce following result −

SimpleXMLElement Object ( [@attributes] => Array ( [type] => Image Processing ) )
php_function_reference.htm
Advertisements