Updating and Deleting XML with PHP DOM
Learn how to update XML element values and delete nodes with PHP DOM using the document structure from earlier examples.
In this article, we will work with the XML document from the previous examples and look at how to update an element's content and delete an element.
The basic idea is simple: first select the elements with getElementsByTagName, then choose the position with item (indexes start at 0), and finally assign the new value through nodeValue.
<?php
$xml = new DOMDocument();
$xml->load('./library.xml'); // Load the library file.
$xml->getElementsByTagName('title')->item(1)->nodeValue = "Test"; // Change the value of the second title element to "Test".
$xml->save('./library.xml'); // Save the file.
?>
The example above shows the simplest update operation. To make the change easier to see, we can print the values before and after the update:
<?php
$xml = new DOMDocument();
$xml->load('./library.xml');
echo "Before";
$books = $xml->getElementsByTagName('book'); // Choose the element to list, e.g. title, author, edition...
foreach ($books as $key => $value) {
echo "
".$key.". element : ".$value->nodeValue;
}
echo "
";
echo "After";
$xml->getElementsByTagName('title')->item(1)->nodeValue = "Test";
$xml->save('./library.xml');
$books = $xml->getElementsByTagName('book'); // Choose the element to list, e.g. title, author, edition...
foreach ($books as $key => $value) {
echo "
".$key.". element : ".$value->nodeValue;
}
?>
You can also use getElementById instead of getElementsByTagName when the XML contains an element such as <element id="123"></element>.
To delete an element:
<?php
$xml = new DOMDocument();
$xml->load('./library.xml'); // Load the library file.
$books = $xml->documentElement;
$book = $books->getElementsByTagName('book')->item(1); // Select the second book element.
$books->removeChild($book); // Delete the selected book element.
$xml->save('./library.xml');
?>