Learning PHP XML DOM

php xml dom guide
10 November 2024

If you want to work with XML documents in PHP, you can use DOM which makes the task much easier. DOM (Document Object Model) is a way to convert XML into a tree structure. This tree represents each of the XML elements as a node, allowing you to easily interact with them. Using DOM provides the ability to easily retrieve data from XML, modify it, or even add new elements.

For instance, let's assume you have an XML file that contains products of a seller. Now, you can use DOM to read this file and gather information about the products, or even add a new product to the XML file for updating.

Using DOM in PHP is very straightforward. You just need to utilize the DOMDocument class to perform this task. In just a few lines of code, you can easily access the XML structure and update the information accordingly. This serves as a simple guide for you to remember what you need. Below, I will provide an example that demonstrates this process more clearly.

Example PHP Code for Working with XML DOM


<?php
$xmlString = '<products><product><name>Laptop</name><price>800</price></product><product><name>Smartphone</name><price>600</price></product></products>';
$dom = new DOMDocument();
$dom->loadXML($xmlString);
$products = $dom->getElementsByTagName('product');
foreach ($products as $product) {
    $name = $product->getElementsByTagName('name')[0]->nodeValue;
    $price = $product->getElementsByTagName('price')[0]->nodeValue;
    echo 'Product: ' . $name . ', Price: ' . $price . "\n";
}
?>

Line-by-line Explanation of the Above Code

<?php – This line indicates the start of the PHP code.
$xmlString – Here, you define a string of XML containing product elements.
$dom = new DOMDocument(); – A new instance of the DOMDocument class is created to handle the XML management.
$dom->loadXML($xmlString); – The XML string is loaded into the DOMDocument instance.
$products = $dom->getElementsByTagName('product'); – This retrieves all product elements from the XML.
foreach ($products as $product) { ... } – This loop iterates through all existing products in the XML.
$name = $product->getElementsByTagName('name')[0]->nodeValue; – Retrieves the name of each product from XML.
$price = $product->getElementsByTagName('price')[0]->nodeValue; – Retrieves the price of each product from XML.
echo 'Product: ' . $name . ', Price: ' . $price . "\n"; – Outputs the product information including name and price.

FAQ

?

How can I add a new element to XML using PHP DOM?

?

How can I change the value of an XML element using PHP DOM?