Home >Backend Development >PHP Tutorial >How to Grab the `href` Attribute of an A Element Using the DOM API?
Grabbing the href Attribute of an A Element: A Comprehensive Guide with DOM
While regex can be challenging for parsing HTML, DOM provides a reliable solution. Here's how to retrieve the href attribute using the DOM API:
Load the HTML
First, load the HTML into a DOMDocument:
$dom = new DOMDocument; $dom->loadHTML($html);
Retrieve the A Elements
Next, retrieve all A elements using getElementsByTagName():
foreach ($dom->getElementsByTagName('a') as $node) { // Do stuff with the A element }
Get the OuterHTML
To get the outerHTML of an A element (including its contents), use saveHtml():
echo $dom->saveHtml($node);
Get the Node Value
To get the text value of an A element, use nodeValue:
echo $node->nodeValue;
Check for the href Attribute
To check if the href attribute exists, use hasAttribute():
echo $node->hasAttribute('href');
Get the href Attribute
To retrieve the href attribute, use getAttribute():
echo $node->getAttribute('href');
Change the href Attribute
To change the href attribute, use setAttribute():
$node->setAttribute('href', 'something else');
Remove the href Attribute
To remove the href attribute, use removeAttribute():
$node->removeAttribute('href');
XPath Query for the href Attribute
You can also query for the href attribute directly using XPath:
$xpath = new DOMXPath($dom); $nodes = $xpath->query('//a/@href');
Iterate through the nodes and perform operations as needed.
Additional Resources
The above is the detailed content of How to Grab the `href` Attribute of an A Element Using the DOM API?. For more information, please follow other related articles on the PHP Chinese website!