PHP DOM XML Update - Delete
Update and Delete Operations with PHP DOM on XML
29.09.2015 · 2 min read
In this article, on the XML we created in previous articles, how do we change the content of a created element and how do we delete it?
Starting quickly, first we specify the element tag with getElementsByTagName, then write which position with item (starts from 0), and then enter our final value with nodeValue.
<?php
$xml = new DOMDocument();
$xml->load('./library.xml'); // we load the library
$xml->getElementsByTagName('title')->item(1)->nodeValue = "Test"; // we change the value of element 1 with the title tag to "Test".
$xml->save('./library.xml'); // we save
?>
Above we see updating the desired element simply. To understand where the change was made:
<?php
$xml = new DOMDocument();
$xml->load('./library.xml');
echo "Before";
$books = $xml->getElementsByTagName('book'); // which element we'll list by, 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'); // which element we'll list by, e.g., title, author, edition...
foreach ($books as $key => $value) {
echo "
".$key.". element : ".$value->nodeValue;
}
?>
Also, instead of getElementsByTagName, you can update the value using getElementById with <element id="123"></element>.
If we want to delete our element:
<?php
$xml = new DOMDocument();
$xml->load('./library.xml'); // we load the library
$books = $xml->documentElement;
$book = $books->getElementsByTagName('book')->item(1); // we select element 1 with the book tag
$books->removeChild($book); // we delete element 1 with the book tag.
$xml->save('./library.xml');
?>