How can DOMDocument be utilized in PHP to extract specific parts of an HTML link, such as the URL and link name?

To extract specific parts of an HTML link, such as the URL and link name, using DOMDocument in PHP, you can load the HTML content into a DOMDocument object, then use DOMXPath to query for the specific elements you are interested in (such as <a> tags), and extract the desired attributes (href for URL, and textContent for link name) from those elements.

$html = &#039;&lt;a href=&quot;https://www.example.com&quot;&gt;Example Link&lt;/a&gt;&#039;;

$dom = new DOMDocument();
$dom-&gt;loadHTML($html);

$xpath = new DOMXPath($dom);
$link = $xpath-&gt;query(&#039;//a&#039;)-&gt;item(0);

$url = $link-&gt;getAttribute(&#039;href&#039;);
$linkName = $link-&gt;textContent;

echo &quot;URL: &quot; . $url . &quot;\n&quot;;
echo &quot;Link Name: &quot; . $linkName;