While learning XML, you have probably started thinking about where it can be used in practice. In this article, I will start answering where and how we can use XML with PHP DOM.

We will continue with the library example from the previous articles.

We will use the following XML structure as our example.

<?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>04</month>
			<day>01</day>
		</date>
	</book>
	<book isbn="9753386203">
		<title>Risaletun-Nushiyye Yunus Emre</title>
		<author role="Translator">Prof. Dr. Umay Turkes Gunay</author>
		<language>Turkish</language>
		<edition>3</edition>
		<date>
			<year>2009</year>
			<month>01</month>
			<day>01</day>
		</date>
	</book>
</books>

Now let's create the XML tree structure with the DOMDocument class and go through the code step by step.

<?php
$xml = new DOMDocument(); // Create the document object.
$xml->encoding = 'UTF-8'; // Set the document encoding to UTF-8.

$books = $xml->createElement('books'); // Create the root books element.

$book = $xml->createElement('book'); // Create the book element.
$book_isbn = $xml->createAttribute('isbn'); // Create the isbn attribute for the book element.
$book_title = $xml->createElement('title'); // Create the title element.
$book_author = $xml->createElement('author'); // ***
$book_role = $xml->createAttribute('role');
$book_language = $xml->createElement('language');
$book_edition = $xml->createElement('edition');
$book_date = $xml->createElement('date');

$book_date_year = $xml->createElement('year'); // ***
$book_date_month = $xml->createElement('month');
$book_date_day = $xml->createElement('day');

$book_date->appendChild($book_date_year); // Add year, month, and day elements under date.
$book_date->appendChild($book_date_month);
$book_date->appendChild($book_date_day);

$book_author->appendChild($book_role); // Add the role attribute to the author element.
$book->appendChild($book_title); // Add title, author, language, and other elements under book.
$book->appendChild($book_author); // ***
$book->appendChild($book_language);
$book->appendChild($book_edition);
$book->appendChild($book_date);
$book->appendChild($book_isbn);

$books->appendChild($book); // Add the book element under books.
$xml->appendChild($books); // Add the books element to the XML document.

$xml->save('./library.xml'); // Save the created XML document.
?>

If we look at the library.xml file created above:

<?xml version="1.0" encoding="UTF-8"?>
<books>
  <book isbn="">
	<title/>
	<author role=""/>
	<language/>
	<edition/>
	<date>
	  <year/>
	  <month/>
	  <day/>
	</date>
  </book>
</books>

At this point, we have created the XML tree structure for the library.

In the next article, I will cover adding content, reading, editing, deleting, and updating data in this XML document.