Read an XML document with SimpleXML
suggest changeYou can parse XML from a string or from an XML file.
From a string
$xml_obj = simplexml_load_string($string);
From a file
$xml_obj = simplexml_load_file('books.xml');
Example of parsing
Considering the following XML:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<name>PHP - An Introduction</name>
<price>$5.95</price>
<id>1</id>
</book>
<book>
<name>PHP - Advanced</name>
<price>$25.00</price>
<id>2</id>
</book>
</books>
This is an example that parses it:
$xml = simplexml_load_string($xml_string);
$books = $xml->book;
foreach ($books as $book) {
$id = $book->id;
$title = $book->name;
$price = $book->price;
print_r ("The title of the book $id is $title and it costs $price." . "\n");
}
This will output:
The title of the book 1 is PHP - An Introduction and it costs $5.95.
The title of the book 2 is PHP - Advanced and it costs $25.00.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents