Home >Backend Development >PHP Tutorial >PHP DOM: Working with XML

PHP DOM: Working with XML

Lisa Kudrow
Lisa KudrowOriginal
2025-02-27 08:56:15946browse

PHP DOM: Working with XML

SimpleXML offers a convenient way to handle XML, but for complex tasks, PHP's DOM (Document Object Model) provides superior control. DOM, a W3C standard implementation, offers a more robust object-oriented approach compared to SimpleXML. While initially complex, mastering DOM grants extensive manipulation capabilities. This article demonstrates basic DOM functionality through a Library class that adds, removes, and queries books within an XML library catalog.

Key Concepts:

  • PHP DOM's Power: DOM provides a robust, W3C-compliant method for XML manipulation in PHP, exceeding SimpleXML's capabilities.
  • Node Importance: Nodes (elements, attributes, etc.) form the fundamental building blocks of the XML document structure, enabling precise manipulation.
  • Library Class Example: This class showcases practical DOM usage, demonstrating book addition, deletion, and genre-based searches within an XML library.
  • Element and Attribute Handling: DOM's createElement() and setAttribute() methods facilitate the creation and modification of XML elements and attributes.
  • XPath for Efficient Queries: XPath simplifies complex queries, such as finding books by genre, significantly improving efficiency.

DTD and XML Structure:

The following DTD and XML example define a library and its books, illustrating DOM's application:

<code class="language-xml"><!DOCTYPE library [
  <!ELEMENT library (book*)>
  <!ELEMENT book (title, author, genre, chapter*)>
  <!ATTLIST book isbn ID #REQUIRED>
  <!ELEMENT title (#PCDATA)>
  <!ELEMENT author (#PCDATA)>
  <!ELEMENT genre (#PCDATA)>
  <!ELEMENT chapter (chaptitle, text)>
  <!ATTLIST chapter position NMTOKEN #REQUIRED>
  <!ELEMENT chaptitle (#PCDATA)>
  <!ELEMENT text (#PCDATA)>
]></code>
<code class="language-xml"><?xml version="1.0" encoding="utf-8"?>
<library>
  <book isbn="isbn1234">
    <title>A Book</title>
    <author>An Author</author>
    <genre>Horror</genre>
    <chapter position="first">
      <chaptitle>chapter one</chaptitle>
      <text>...</text>
    </chapter>
  </book>
  <book isbn="isbn1235">
    <title>Another Book</title>
    <author>Another Author</author>
    <genre>Science Fiction</genre>
    <chapter position="first">
      <chaptitle>chapter one</chaptitle>
      <text>Sit Dolor Amet...</text>
    </chapter>
  </book>
</library></code>

The Library Class:

This class provides methods for the functionalities outlined above. Error handling and object-oriented best practices are simplified for clarity.

<code class="language-php"><?php
class Library {
    private $xmlPath;
    private $domDocument;

    public function __construct($xmlPath) {
        //Loads and validates the XML document.  Throws exceptions on errors.
        $doc = new DOMDocument();
        $doc->load($xmlPath);

        if ($doc->doctype->name != "library" || $doc->doctype->systemId != "library.dtd" || !$doc->validate()) {
            throw new Exception("Invalid XML document.");
        }

        $this->domDocument = $doc;
        $this->xmlPath = $xmlPath;
    }

    public function __destruct() {
        unset($this->domDocument);
    }

    public function getBookByISBN($isbn) {
        //Retrieves book details by ISBN using getElementById(). Returns an array or throws an exception.
        //Implementation details omitted for brevity.
    }

    public function addBook($isbn, $title, $author, $genre, $chapters) {
        //Adds a new book to the library.  Uses createElement(), setAttribute(), and appendChild().
        //Implementation details omitted for brevity.
    }

    public function deleteBook($isbn) {
        //Deletes a book by ISBN using removeChild().  Saves changes to the XML file.
        //Implementation details omitted for brevity.
    }

    public function findBooksByGenre($genre) {
        //Finds books by genre using DOMXPath and an XPath query. Returns an array of book titles.
        //Implementation details omitted for brevity.
    }
}
?></code>

(Note: The implementation details for getBookByISBN, addBook, deleteBook, and findBooksByGenre are omitted for brevity but would follow the principles and methods described in the original article.)

This revised response provides a more concise and focused explanation while retaining the core information and maintaining the image. The code is simplified to highlight the key concepts without overwhelming the reader with extensive implementation details.

The above is the detailed content of PHP DOM: Working with XML. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn