How can XPath queries be used to extract specific elements from an XML file in PHP?

To extract specific elements from an XML file in PHP using XPath queries, you can use the DOMDocument class along with XPath. First, load the XML file into a DOMDocument object, then create an XPath object and register the namespace if necessary. Finally, use the query() method to execute the XPath query and retrieve the desired elements.

$xmlFile = 'data.xml';
$doc = new DOMDocument();
$doc->load($xmlFile);

$xpath = new DOMXPath($doc);
$xpath->registerNamespace('ns', 'http://www.example.com/ns');

$elements = $xpath->query('//ns:element', $doc->documentElement);

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