Search code examples
phpxmlsimplexml

How to get attributes of XML root element using SimpleXMLElement


I have an XML file with the root element name wwwjob. This root element contains attributes, I need to access the value of the 'method' attribute to be able to update various database entries.

This is a little bit of a learning curve at the moment.

<?xml version="1.0" encoding="iso-8859-1"?>
 <wwwjob id="32cca11IACH" method="Delete">
   some more xml stuff
 </wwwjob>

Ive tried:

<?php $xml = $vacancyXML->wwwjob['method']; ?>

This just gave me 'NULL'.

Ive also tried:

 <?php $xml = $vacancyXML->getName(); ?>

This just spits out the name 'wwwjob'.

I need to store the method (Delete/Update/Add) as a variable for use in later parts of the function.

Thanks


Solution

  • When loadinG to simplexml, attributes of the root element became attributes of the simpleXml object. So, you can get it just

    $str = '<?xml version="1.0" encoding="iso-8859-1"?>
     <wwwjob id="32cca11IACH" method="Delete">
     </wwwjob>';
    $vacancyXML = simplexml_load_string($str);
    
    echo $vacancyXML['method']; // Delete
    

    demo