简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM