While examining XML, you've probably thought "I'll use this here like this." I'll try to answer questions about where and how to use it.

Let's continue with the library example as we started with.

We'll use the following structure as an example XML.

<?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>

Let's create the XML tree structure with the DOMDocument Class. Let's go through the code line by line.

<?php
$xml = new DOMDocument(); // We create the object
$xml->encoding = 'UTF-8'; // We set the object's encoding to UTF-8

$books = $xml->createElement('books'); // We create a root element called books

$book = $xml->createElement('book'); // We create the book element
$book_isbn = $xml->createAttribute('isbn'); // We create the isbn attribute for the book element
$book_title = $xml->createElement('title'); // We 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); // We add year, month, day elements under the date element.
$book_date->appendChild($book_date_month);
$book_date->appendChild($book_date_day);

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

$books->appendChild($book); // We add the book element under the books element
$xml->appendChild($books); // We add the books element under XML

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

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

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

We've created the library XML tree structure.

In my next article, I'll try to cover adding content, reading, editing, deleting, and updating operations on the created XML.