Load the HTML content into a DOMDocument object.

To get HTML tag attribute values in PHP, you can use the DOMDocument class, a built-in PHP class for parsing HTML documents. Here’s a step-by-step guide on how to achieve this:

  1. Load the HTML Document:
    You need to load the HTML document (either from a file or a string) into a DOMDocument object.
  2. Select the Desired Element:
    Use DOMDocument methods to select the HTML element whose attribute value you want to retrieve. This could be based on the element’s tag name, class, id, or other attribute.
  3. Get the Attribute Value:
    Once you have selected the element, use DOMElement methods to access and retrieve the attribute value.

Here’s an example code that demonstrates how to get the value of the href attribute from an anchor (<a>) tag in an HTML document:


// Sample HTML content (you can load from a file or URL as well)
$htmlContent = '<div>
                    <a href="https://example.com">Click here</a>

// Create a new DOMDocument object
$dom = new DOMDocument();

// Load the HTML content into the DOMDocument

// Get all anchor tags in the HTML
$anchorTags = $dom->getElementsByTagName('a');

// Loop through the anchor tags to get the href attribute value
foreach ($anchorTags as $anchorTag) {
    $hrefValue = $anchorTag->getAttribute('href');
    echo "Value of 'href' attribute: " . $hrefValue . "<br>";


In this example, we load the HTML content into the DOMDocument object and then use getElementsByTagName to select all the anchor tags (<a>) in the document. We then loop through each anchor tag and use the getAttribute method to get the value of the href attribute, which is then printed on the screen.

You can adapt this code to retrieve attribute values from other types of HTML tags or based on different attributes by adjusting the tag name or using other DOMDocument methods accordingly.