Anna Wellington
Anna Wellington

Reputation: 323

Retrieve XML data using PHP

I'm having a hard time retrieving below xml data separately using PHP.

    <?xml version="1.0" encoding="UTF-8"?>
    <document>
       <data>
          <headertext>Welcome</headerp>
          <postheadertext>Travellers</headers>
       </data>
    </document>

This is the php code written to retrieve the xml data & this doesn't work.

<a id="titleyellow">
<?php$xml=simplexml_load_file("storeddata.xml") or die("Error: Cannot create object");echo $xml->headertext;?>
</a>

<a id="titlewhite">
<?php$xml=simplexml_load_file("storeddata.xml") or die("Error: Cannot create object");echo $xml->postheadertext;?>
</a>

The xml data should be as it is & i am looking for a code that could retrieve this data to display seperately within HTML content.

I Really appreciate whoever can assist me with this. Thanks heaps!

Best regards David

Upvotes: 0

Views: 215

Answers (2)

Syed Imran Ertaza
Syed Imran Ertaza

Reputation: 175

When you load the xml file using the php simplexml_load_file function to a variable. The veritable becomes an object.

<?php 
$xml=simplexml_load_file("storeddata.xml");
?>

So, in your case, the $xml variable becomes a multi-level object where every elements of xml file are key of the object.

To access the data of the element, need to call like this bellow code.

echo $xml->data->headertext . "<br>";

Here, data is the key of $xml object. headertext is the key of data.

The output will be the value of headertext = Welcome

Upvotes: 0

Gordon
Gordon

Reputation: 316969

It's $xml->data->headertext and $xml->data->postheadertext obviously. There is a <data> element before the header elements. Not sure why you think you can omit that.

Check http://php.net/manual/en/simplexml.examples-basic.php again

Upvotes: 2

Related Questions