Read a XML document with DOMDocument

suggest change

Similarly to the SimpleXML, you can use DOMDocument to parse XML from a string or from a XML file

1. From a string

$doc = new DOMDocument();
$doc->loadXML($string);

2. From a file

$doc = new DOMDocument();
$doc->load('books.xml');// use the actual file path. Absolute or relative

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 a example code to parse it

$books = $doc->getElementsByTagName('book');
foreach ($books as $book) {
    $title = $book->getElementsByTagName('name')->item(0)->nodeValue;
    $price = $book->getElementsByTagName('price')->item(0)->nodeValue;
    $id = $book->getElementsByTagName('id')->item(0)->nodeValue;
    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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


XML:
* XML
* Read a XML document with DOMDocument

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR