How can XPath be used to extract both the href value and the text content from an <a> tag in PHP?

To extract both the href value and the text content from an <a> tag using XPath in PHP, you can use the DOMXPath class to query the XML document and retrieve the desired values. You can use XPath expressions to select the href attribute and text content of the <a> tag. By iterating through the results, you can extract both the href value and the text content from each <a> tag.

// Load the HTML content into a DOMDocument
$html = &#039;&lt;a href=&quot;https://example.com&quot;&gt;Example&lt;/a&gt;&#039;;
$doc = new DOMDocument();
$doc-&gt;loadHTML($html);

// Create a new DOMXPath instance
$xpath = new DOMXPath($doc);

// Use XPath to select all &lt;a&gt; tags
$aTags = $xpath-&gt;query(&#039;//a&#039;);

// Iterate through each &lt;a&gt; tag to extract href value and text content
foreach ($aTags as $aTag) {
    $href = $aTag-&gt;getAttribute(&#039;href&#039;);
    $textContent = $aTag-&gt;textContent;
    
    echo &quot;Href: $href, Text Content: $textContent\n&quot;;
}