How can one effectively retrieve attributes like href from h2 and h3 tags in PHP DOM manipulation?

To effectively retrieve attributes like href from h2 and h3 tags in PHP DOM manipulation, you can use the DOMDocument and DOMXPath classes. First, load the HTML content into a DOMDocument object, then use DOMXPath to query for h2 and h3 tags and extract their href attributes.

<?php
$html = '<html><body><h2><a href="link1.html">Heading 2</a></h2><h3><a href="link2.html">Heading 3</a></h3></body></html>';

$dom = new DOMDocument();
$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

$h2Nodes = $xpath->query('//h2/a');
foreach ($h2Nodes as $node) {
    echo $node->getAttribute('href') . "\n";
}

$h3Nodes = $xpath->query('//h3/a');
foreach ($h3Nodes as $node) {
    echo $node->getAttribute('href') . "\n";
}
?>