Parsing XML elements and attributes with PHP

Use the PHP class XMLReader to parse an XML file and read elements and attributes


/**
 * simpleXMLParser.php - Reading XML elements and attributes with PHP
 * @author freedelta http://freedeta.free.fr
 */

/**
 * XML_DATA.xml - XML sample file to be parsed
 
 
 1234567
 
 
 
 
 
 
 Xml data to test attributes and elements reading with PHP
 
*/

$reader = new XMLReader();
$reader->open("XML_DATA.xml");

while($reader->read()){ // Loop through XML file

    // Elements
    if($reader->nodeType == XMLReader::ELEMENT && $reader->name!="ROOT"){ // Root node
        $elm=$reader->name;    
        if ($reader->hasAttributes){ // Attributes
            while ($reader->moveToNextAttribute()) {
                print "
Element: $elm with ATTRIBUTES: attribute name: ".$reader->name." value: ".$reader->value;
                
            }
              
        }
            
        $reader->read();// Avance reader to the next node   
        if(trim($reader->value)!=""){
            print "
Element: $elm with DATA only, value: ".$reader->value;
        }        
    }

}

$reader->close();

?>