Tags
Asked 3 years ago
30 Jun 2021
Views 203
Marcelina

Marcelina posted

Reading an XML File in PHP

Reading an XML File in PHP
sqltreat

sqltreat
answered May 4 '23 00:00

To read an XML file in PHP, we can use the SimpleXML class that is built into PHP. Here's an example of how we can read an XML file and access its data:


$xml = simplexml_load_file('file.xml');

// Accessing data in the XML file
echo "Title: " . $xml->title . "<br>";
echo "Author: " . $xml->author . "<br>";
echo "Year: " . $xml->year . "<br>";
echo "Price: " . $xml->price . "<br>";

// Looping through nodes
foreach ($xml->book as $book) {
  echo "Title: " . $book->title . "<br>";
  echo "Author: " . $book->author . "<br>";
  echo "Year: " . $book->year . "<br>";
  echo "Price: " . $book->price . "<br><br>";
}

In the example above, we first use the simplexml_load_file() function to load the XML file into an object. We can then access the data in the XML file using object notation.

We can also loop through the nodes in the XML file using a foreach loop.

The SimpleXML class provides many other useful methods for working with XML files in PHP, such as simplexml_load_string() for loading an XML string into an object, and asXML() for converting an object back into an XML string.
Post Answer