$dom = new DomDocument("1.0", "UTF-8"); $root = $dom->createElement("library"); $dom->appendChild($root); $book = $dom->createElement("book"); $root->appendChild($book); $title = $dom->createElement("title", "The Lord of the Rings"); $book->appendChild($title); $author = $dom->createElement("author", "J.R.R. Tolkien"); $book->appendChild($author); echo $dom->saveXML();
$dom = new DomDocument(); $dom->load("books.xml"); $books = $dom->getElementsByTagName("book"); foreach ($books as $book) { $titles = $book->getElementsByTagName("title"); $title = $titles->item(0)->nodeValue; $authors = $book->getElementsByTagName("author"); $author = $authors->item(0)->nodeValue; echo $title . " by " . $author . "In this example, we load an XML document "books.xml" and retrieve all the "book" elements. We then loop through each "book" element, retrieve the "title" and "author" elements and output them. DomDocument is a useful library for parsing and manipulating XML documents in PHP applications. It provides a simple and intuitive API for working with XML documents and is included in the core PHP installation.
"; }