Writing

Build a new XML document with DOMDocument, then write it to disk with save(). The example below constructs book.xml: a document with a top-level comment, a root <book> element, and a nested <part> element whose title attribute is registered as an ID attribute via setIdAttribute(). One <chapter> child is appended to <part> for each entry in a PHP array.

<!DOCTYPE html>
<html><head></head><body><?php

$doc = new DOMDocument("1.0","UTF-8");
$comment=$doc->createComment("This is 'book.xml'.");
$doc->appendChild($comment);
$book=$doc->createElement("book");
$doc->appendChild($book);
$part1 = new DOMElement("part");
$book->appendChild($part1);
$part1->setAttribute("title","Core");
$part1->setIdAttribute("title",true);
$chapters = ["HTML","CSS","JavaScript","PHP","SQL","XML"];
foreach ($chapters as $chapter){
   $c = new DOMElement("chapter",$chapter);
   $part1->appendChild($c);
}
$doc->save("book.xml");

?></body></html>
Opening the resulting book.xml in an XML-aware viewer shows the tree built above – a book root containing a part element with six chapter children:

Tree view of the generated book.xml document showing a book element containing chapters for HTML, CSS, JavaScript, PHP, SQL, and XML