How can Xpath and DOMXPath be utilized in PHP to extract specific values from XML files?

To extract specific values from XML files in PHP, you can use Xpath and DOMXPath. Xpath allows you to navigate through the XML document and select specific nodes based on their location or attributes. DOMXPath is a class in PHP that allows you to query XML documents using Xpath expressions.

$xmlString = file_get_contents('example.xml');
$xml = new DOMDocument();
$xml->loadXML($xmlString);

$xpath = new DOMXPath($xml);
$nodes = $xpath->query('//book[@category="fiction"]/title');

foreach ($nodes as $node) {
    echo $node->nodeValue . "\n";
}