Using the PHP DOM Class, we'll focus on how to add data to the XML structure we created and how to read this data.

Now, unlike when creating the data structure before, we'll use setAttribute instead of createAttribute.

<?php
$xml = new DOMDocument();
$xml->encoding = 'UTF-8';

$books = $xml->createElement('books');

$book = $xml->createElement('book');
$book_isbn = $book->setAttribute('isbn', '9759954949'); // We add the isbn attribute to the book element and assign it a value.
$book_title = $xml->createElement('title', 'Yunus Emre Divani'); // We 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's time to read the data from the XML file we created. First, let's read the XML and display it as we saved it.

<?php
$xml = new DOMDocument();
$xml->load('./library.xml');
print $xml->saveXML();
?>

When you want to view this in your browser, there's a high probability you'll see something like [ Yunus Emre Divani Selim Yagmur Turkish 8 2014 4 1 ]. If you look at the source code, you'll see the XML you created.

When there are many elements:

<?php
$xml = new DOMDocument();
$xml->load('./library.xml');

$books = $xml->getElementsByTagName('book'); // which element we'll list by, 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

You can list the book elements under books and add new elements to them.