How can SimpleXML and XPath be effectively used together in PHP for XML manipulation?

SimpleXML can be used to parse and manipulate XML data in PHP, while XPath can be used to navigate and query XML documents. By combining SimpleXML and XPath, you can effectively target specific elements within an XML document for manipulation. This can be done by using XPath expressions to locate the desired elements and then using SimpleXML methods to make the necessary changes.

$xml = simplexml_load_file('data.xml');

// Use XPath to find all <book> elements with <title> containing 'PHP'
$books = $xml->xpath("//book[contains(title, 'PHP')]");

// Loop through the found <book> elements and update their <price> element
foreach ($books as $book) {
    $book->price = '19.99';
}

// Save the modified XML back to a file
$xml->asXML('updated_data.xml');