DOMDocument

Last updated on

In PHP, if you're working with XML files, you’ll probably work with DOMDocument. It is a powerful class, enabling you to read, modify XML data, and save further modifications. With that, you can easily manipulate even complicated structures.

Additionally, some helper methods used along with DOMDocument include the XML DOM parser, which enhances your ability to process, parse, and validate flexible XML files with more control.

Whether you're working with API integrations or just need a surefire way to handle XML data, these utilities offer core functionality.

Let’s dive into DOMDocument, break down its main features, and explore its integration with the XML DOM Parser for full XML manipulation in PHP.  

Getting Started with PHP DOMDocument

First and foremost, of course, is to get the class started to begin using DOMDocument. The DOMDocument class in PHP offers you methods to create, load, and alter XML. Here’s how you get started:  

$doc = new DOMDocument();

These few lines instantiate the DOMDocument object. Once created, you can load an XML file, load XML from a string, or even fetch XML from a URL. Say you have a local XML file to load; you can do it like this:  

$doc->load('example.xml');

Once loaded, the XML data becomes available via DOMDocument methods. You will see in the next section how to navigate XML nodes and begin to use your data. 

PHP DOMDocument: Traversing the XML Nodes

XML documents have a tree structure, where nodes represent the branches and leaves of the tree. Working with such a structure is pretty easy with DOMDocument: you can literally get hold of each and every part of your XML document.

First, you’ll want to get the root element that will serve as an entry point to the document:  

$root = $doc->documentElement;

Starting from this root node, you can access child elements by tag name via getElementsByTagName(). This function returns a list of elements with the given tag, so if you have multiple tags like <item>, here’s how to access each one:  

$items = $doc->getElementsByTagName('item');
foreach ($items as $item) {
    echo $item->nodeValue;
}

This works with large-sized XML files containing repeated tags because it lets you loop through and manage each element directly.

Next, we’ll discuss how modifications are done to these nodes, giving you full control over XML content.

Editing XML Data with DOMDocument in PHP

Once you have loaded an XML document, you are by no means limited to just reading its contents. With DOMDocument, you are able to add new elements, change existing elements, and even remove nodes.

Suppose you wish to add a new child node to the root element. You would call createElement() to create the new node, then appendChild() to add this:  

$newElement = $doc->createElement('newTag', 'Content goes here');
$doc->documentElement->appendChild($newElement);

This code creates an element called newTag with specified content and appends it to the root element. To delete a node, you locate the node and call removeChild() on its parent: 

$nodeToRemove = $doc->getElementsByTagName('item')->item(0);
$doc->documentElement->removeChild($nodeToRemove);

Whether adding, changing, or removing nodes, DOMDocument provides all the tools and methods you need to dynamically revise XML data. Next, we will walk through saving and outputting the modified XML.  

Saving and Exporting Your XML Data

Now, after editing your XML, you’ll most likely want to write the changes back or output the changed XML immediately. DOMDocument offers two methods in this regard: save() to save into a file and saveXML() to return XML as a string.  

To save the modified XML to a file, use:

$doc->save('updated_example.xml');

Or, if you want it output as a string, you can use:

echo $doc->saveXML();

This flexibility allows you to handle XML data as needed—save it locally, send it in an HTTP response, etc.

In the next section, we’ll look at how to validate XML files using the XML DOM Parser to ensure accuracy and coherence.

Validating XML Using the XML DOM Parser

The principal objective of XML, especially if you’re pulling your data from external sources, is validation. The XML DOM Parser, coupled with DOMDocument, will help ensure that your XML is in the required structure set out by either a DTD or XSD.

For validation against DTDs, before loading the document, use the following line to set the validateOnParse property to true:

$doc->validateOnParse = true;
if ($doc->load('example.xml')) {
    echo "XML is valid!";
} else {
    echo "XML failed validation.";
}

If you’re using an XSD, use the schemaValidate() method. Either of these methods will ensure your XML structure matches the expected format, preventing issues later on. 

Practical Applications of DOMDocument and XML DOM Parser

DOMDocument and XML DOM Parser are not only vital but also find major use in a variety of applications, especially when working with APIs, configuration data, or reporting. For example, if your application pulls data from an XML-based API, you can use DOMDocument to fetch, parse, and display that data in PHP.  

Suppose you are working with weather data from an API that returns XML. You could load the response into DOMDocument and parse it as follows:  

$doc = new DOMDocument();
$doc->load('https://api.example.com/weather.xml');
$temperatures = $doc->getElementsByTagName('temperature');
foreach ($temperatures as $temp) {
    echo $temp->nodeValue;
}

The above example shows the practical use of the DOMDocument class in a real-life project, giving you the opportunity to process and present XML data meaningfully.

Wrapping Up

PHP’s DOMDocument and XML DOM Parser provide all the functionality needed for handling XML—from loading and navigating XML to editing, validating, and saving data.

These utilities are mainstays in any serious PHP developer's toolkit, granting control over complex tasks for nearly any scenario.Understanding DOMDocument and XML DOM Parser can help you handle XML data with much greater ease than normally possible.

If you need to see more tutorials in PHP just click here.  

Frequently Asked Questions (FAQs)

  • What is PHP DOMDocument used for?

    DOMDocument is a PHP class used to read, manipulate, and save XML data. It enables developers to work with XML documents by providing methods to load XML files, edit nodes, and validate XML structure.
  • How do I create a new XML file with PHP DOMDocument?

    First, instantiate the DOMDocument class, then use createElement and appendChild to build the XML structure, and finally, use save() to save it to a file.
    $doc = new DOMDocument();
    $root = $doc->createElement("root");
    $doc->appendChild($root);
    $child = $doc->createElement("child", "This is a child node");
    $root->appendChild($child);
    $doc->save("newfile.xml");
    
  • How can I load an XML file in PHP with DOMDocument?

    Use the load() method on a DOMDocument instance, passing the XML file path as an argument.
    $doc = new DOMDocument();
    $doc->load("example.xml");
    
  • How do I retrieve XML elements by tag name in DOMDocument?

    Use getElementsByTagName() to retrieve elements by their tag name. This method returns a list of elements with the specified tag.
    $doc = new DOMDocument();
    $doc->load("example.xml");
    $elements = $doc->getElementsByTagName("item");
    foreach ($elements as $element) {
        echo $element->nodeValue;
    }
    
  • How can I validate XML with DOMDocument in PHP?

    To validate XML, you can use validateOnParse for DTD validation or schemaValidate() for XML Schema validation. This ensures the XML matches a predefined structure.
    $doc = new DOMDocument();
    $doc->validateOnParse = true;
    if ($doc->load("example.xml")) {
        echo "XML is valid!";
    } else {
        echo "XML validation failed.";
    }
    
  • How do I add a new node to an existing XML document?

    Use createElement() to create the new node, and appendChild() to add it to a parent node.
    $doc = new DOMDocument();
    $doc->load("example.xml");
    $newNode = $doc->createElement("newTag", "Content for new tag");
    $doc->documentElement->appendChild($newNode);
    $doc->save("example.xml");
    
  • Can I delete an XML node in PHP DOMDocument?

    Yes, you can remove an XML node using removeChild(). Locate the node and call removeChild() on its parent.
    $doc = new DOMDocument();
    $doc->load("example.xml");
    $nodeToRemove = $doc->getElementsByTagName("item")->item(0);
    $doc->documentElement->removeChild($nodeToRemove);
    $doc->save("example.xml");
    
  • How do I convert an XML document to a string in PHP?

    Use saveXML() to output the entire XML document as a string.
    $doc = new DOMDocument();
    $doc->load("example.xml");
    echo $doc->saveXML();
    
  • How can I handle errors in DOMDocument?

    Enable error handling by setting libxml_use_internal_errors(true) before loading the XML, allowing you to retrieve errors with libxml_get_errors().
    libxml_use_internal_errors(true);
    $doc = new DOMDocument();
    $doc->load("example.xml");
    $errors = libxml_get_errors();
    foreach ($errors as $error) {
        echo $error->message;
    }
    libxml_clear_errors();
    
Share on: