Creating and Reading XML with PHP DOM
Learn how to add data to an XML structure and read it with PHP DOM through practical examples.
In this article, we will use the PHP DOM class to add data to the XML structure we created earlier and then read that data back.
This time, instead of using createAttribute as we did when building the structure, we will use setAttribute.
<?php
$xml = new DOMDocument();
$xml->encoding = 'UTF-8';
$books = $xml->createElement('books');
$book = $xml->createElement('book');
$book_isbn = $book->setAttribute('isbn', '9759954949'); // Add the isbn attribute to the book element and assign a value.
$book_title = $xml->createElement('title', 'Yunus Emre Divani'); // Assign a value to the title element.
$book_author = $xml->createElement('author', 'Selim Yagmur'); // **
$book_role = $book_author->setAttribute('role', 'Editor'); // *
$book_language = $xml->createElement('language', 'Turkish'); // **
$book_edition = $xml->createElement('edition', 8); // **
$book_date = $xml->createElement('date'); // **
$book_date_year = $xml->createElement('year', 2014); // **
$book_date_month = $xml->createElement('month', 04); // **
$book_date_day = $xml->createElement('day', 01); // **
$book_date->appendChild($book_date_year);
$book_date->appendChild($book_date_month);
$book_date->appendChild($book_date_day);
$book_author->appendChild($book_role);
$book->appendChild($book_title);
$book->appendChild($book_author);
$book->appendChild($book_language);
$book->appendChild($book_edition);
$book->appendChild($book_date);
$book->appendChild($book_isbn);
$books->appendChild($book);
$xml->appendChild($books);
$xml->save('./library.xml');
?>
The XML output is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book isbn="9759954949">
<title>Yunus Emre Divani</title>
<author role="Editor">Selim Yagmur</author>
<language>Turkish</language>
<edition>8</edition>
<date>
<year>2014</year>
<month>4</month>
<day>1</day>
</date>
</book>
</books>
Now it is time to read data from the XML file we created. First, let's load the XML and print it exactly as it was saved.
<?php
$xml = new DOMDocument();
$xml->load('./library.xml');
print $xml->saveXML();
?>
When you view this in a browser, you will probably see plain text similar to [ Yunus Emre Divani Selim Yagmur Turkish 8 2014 4 1 ]. If you view the page source, you will see the XML structure you created.
When there are multiple elements:
<?php
$xml = new DOMDocument();
$xml->load('./library.xml');
$books = $xml->getElementsByTagName('book'); // Choose the element to list, e.g. title, author, edition...
foreach ($books as $key => $value) {
echo $key.". element : ".$value->nodeValue."
";
}
?>
Screen output:
0. element : Yunus Emre Divani Selim Yagmur Turkish 8 2014 04 01
1. element : Risaletun-Nushiyye Yunus Emre Prof. Dr. Umay Turkes Gunay Turkish 3 2009 01 01
This way, you can list the book elements under books and add new elements when needed.