You can modify SimpleXMLElement objects in the following ways:

>Changing the values of text and attributes

>Removing text, attribute, or element nodes

>Adding new nodes and attributes

Let’s take a brief look at each of them.

Changing the values of text and attributes

This is very easy. You simply assign the new value to the property you want to change. The following code (in modify_xml_01.php) loads inventory2.xml, reduces the price of the paperback version of each book by ten percent, and displays the modified XML onscreen:

$xml = simplexml_load_file('inventory2.xml');
foreach ($xml->book as $book) {
// Remove the dollar sign
$reduced = substr($book->price->paperback, 1);
// Multiply by .9 to give 10% discount
$reduced *= .9;
// Format the number, and reassign it to the original property
$book->price->paperback = '$' . number_format($reduced, 2);
}
header ('Content-Type: text/xml');
echo $xml->asXML();

The inline comments explain what’s going on here. The prices in the <paperback> nodes are formatted as U.S. currency, so the substr() function removes the dollar sign before the value is multiplied by 0.9. The dollar sign is then replaced, and the number formatted to two decimal places with number_format().

Removing nodes and values

This is also very easy: use unset(). The following code (in modify_xml_02.php) removes
the isbn13 attribute, as well as the <publisher>, <price>, and <description> nodes:
$xml = simplexml_load_file('inventory2.xml');
foreach ($xml->book as $book) {
unset($book['isbn13']);
unset($book->publisher);
unset($book->price);
unset($book->description);
}
header ('Content-Type: text/xml');
echo $xml->asXML();

If, for any reason, you want to preserve a node but remove its value, simply change its value to an empty string instead of using unset().

Adding attributes

The intuitively named addAttribute() method adds an attribute to an existing element tag.
It takes two arguments: the name of the attribute and the value to be assigned. The following
code (in modify_xml_03.php) shows addAttribute() in action, adding a category
attribute to each <book> node:
$xml = simplexml_load_file('inventory2.xml');
foreach ($xml->book as $book) {
if (strpos($book->title, 'PHP') !== false) {
$book->addAttribute('category', 'PHP');
} else {
$book->addAttribute('category', 'Web design');
}
}
header ('Content-Type: text/xml');
echo $xml->asXML();
This uses strpos() to detect whether the <title> node contains “PHP”. Since “PHP” could be at the start of the title, which returns a value of 0, it’s necessary to use false with the not identical operator (!==) to avoid getting a false negative.