Google News
logo
Use simplexml_load_file() to read XML data from a file in PHP
In the following example of PHP program that uses `simplexml_load_file()` to read XML data from a file :
Program :
<?php
// File path
$file = 'data.xml';

// Load XML data from file
$xml = simplexml_load_file($file);

// Access and display data
foreach ($xml->children() as $child) {
    echo "Name: " . $child->name . "<br>";
    echo "Age: " . $child->age . "<br>";
    echo "Gender: " . $child->gender . "<br><br>";
}
?>
In the above program, we first specify the path of the XML file to be read. We then use the `simplexml_load_file()` function to load the XML data from the file into a SimpleXMLElement object, which we can then use to access and display the data in the XML file.

We then use a `foreach` loop to iterate through the children of the root element, and use the `->` operator to access the values of the various child elements. In this example, we assume that the XML file contains child elements with `name`, `age`, and `gender` attributes, and we display the values of these attributes for each child element.