DOMDocument
Last updated onIn PHP, if you're working with XML files, you’ll probably work with
. 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. DOMDocument
Additionally, some helper methods used along with
include the XML DOM parser, which enhances your ability to process, parse, and validate flexible XML files with more control. DOMDocument
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
class in PHP offers you methods to create, load, and alter XML. Here’s how you get started: DOMDocument
$doc = new DOMDocument();
These few lines instantiate the
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: DOMDocument
$doc->load('example.xml');
Once loaded, the XML data becomes available via
methods. You will see in the next section how to navigate XML nodes and begin to use your data. DOMDocument
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
: you can literally get hold of each and every part of your XML document. DOMDocument
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
. This function returns a list of elements with the given tag, so if you have multiple tags like getElementsByTagName()
, here’s how to access each one: <item>
$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
, you are able to add new elements, change existing elements, and even remove nodes. DOMDocument
Suppose you wish to add a new child node to the root element. You would call
to create the new node, then createElement()
to add this: appendChild()
$newElement = $doc->createElement('newTag', 'Content goes here');
$doc->documentElement->appendChild($newElement);
This code creates an element called
with specified content and appends it to the root element. To delete a node, you locate the node and call newTag
on its parent: removeChild()
$nodeToRemove = $doc->getElementsByTagName('item')->item(0);
$doc->documentElement->removeChild($nodeToRemove);
Whether adding, changing, or removing nodes,
provides all the tools and methods you need to dynamically revise XML data. Next, we will walk through saving and outputting the modified XML. DOMDocument
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.
offers two methods in this regard: DOMDocument
to save into a file and save()
to return XML as a string. saveXML()
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
, will help ensure that your XML is in the required structure set out by either a DTD or XSD.DOMDocument
For validation against DTDs, before loading the document, use the following line to set the
property to true:validateOnParse
$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
method. Either of these methods will ensure your XML structure matches the expected format, preventing issues later on. schemaValidate()
Practical Applications of DOMDocument and XML DOM Parser
and DOMDocument
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
to fetch, parse, and display that data in PHP. DOMDocument
Suppose you are working with weather data from an API that returns XML. You could load the response into
and parse it as follows: DOMDocument
$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
class in a real-life project, giving you the opportunity to process and present XML data meaningfully. DOMDocument
Wrapping Up
PHP’s
and DOMDocument
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
and XML DOM Parser can help you handle XML data with much greater ease than normally possible. DOMDocument
If you need to see more tutorials in PHP just click here.
Frequently Asked Questions (FAQs)
What is PHP DOMDocument used for?
How do I create a new XML file with PHP DOMDocument?
How can I load an XML file in PHP with DOMDocument?
How do I retrieve XML elements by tag name in DOMDocument?
How can I validate XML with DOMDocument in PHP?
How do I add a new node to an existing XML document?
Can I delete an XML node in PHP DOMDocument?
How do I convert an XML document to a string in PHP?
How can I handle errors in DOMDocument?