Tags
Asked 3 years ago
30 Jun 2021
Views 230
Deborah

Deborah posted

How to read XML file data with Php?

How to read XML file data with Php?
iptracker

iptracker
answered Apr 28 '23 00:00

You can read the data from an XML file using PHP by using the SimpleXML extension. Here's a basic example of how you can use SimpleXML to read data from an XML file:



// Load the XML file
$xml = simplexml_load_file('data.xml');

// Access the data
echo $xml->first_element->second_element;

In the example above, the simplexml_load_file() function is used to load the contents of the XML file into a SimpleXMLElement object. You can then access the data in the XML file by using object properties to navigate through the XML tree.

For example, if the XML file contains a list of products, you could loop through the products like this:



foreach ($xml->product as $product) {
    echo $product->name . ': ' . $product->price . '<br>';
}

In this example, the foreach loop is used to iterate through each <product> element in the XML file. The name and price of each product are then displayed on the page.
Post Answer