How to extract img src, title and alt from html using php?

How to extract img src, title and alt from html using php?

  1. Blog
  2. 15 November 2026
  3. 2 min read

Stefan Bogdanescu

Founder & Senior Architect

Parsing Images in HTML Without Regex

Extracting attributes from an HTML document is a classic problem for developers. The immediate instinct is often to reach for a regular expression. While regex can work for simple, predictable patterns like <img src="..." alt="...">, it quickly breaks down when dealing with the reality of web markup. Attributes have no fixed order; they might appear as alt before src, or be omitted entirely if not required by the schema. Furthermore, HTML5 allows quotes to be absent on certain attributes, and values can contain spaces or special characters that regex engines struggle to capture reliably without becoming extremely verbose and fragile.

The elegant solution is to treat HTML as a structured document rather than a string of text. In PHP, the DOMDocument class provides a robust API for parsing these structures. Unlike simple string manipulation, the DOM parser understands hierarchy and attributes natively. It handles edge cases like self-closing tags, missing quotes, and attribute ordering automatically.

To begin, you must load your HTML content into a DOMDocument instance. However, there is a critical detail specific to PHP's implementation of this class: it expects well-formed XML by default. If your HTML contains special characters like < or &, or if the document lacks a closing body tag (common in minified scripts), parsing will fail with a warning and return an empty result. You must enable support for non-well-formed HTML using the libxml_use_internal_errors(true) function before loading the string. This suppresses PHP warnings that would otherwise clutter your output while allowing the parser to proceed gracefully.

Once the document is loaded, you can query it using XPath or by iterating through nodes. For extracting image data specifically, an XPath query targeting //img elements is efficient and readable. You can then loop through each resulting node to retrieve the attributes you need.

Here is a practical implementation pattern:

$htmlString = '<img src="/image/fluffybunny.jpg" title="Harvey the bunny" alt="a cute little fluffy bunny" />';

// Enable handling of malformed HTML and suppress warnings
libxml_use_internal_errors(true);

$dom = new DOMDocument();
$dom->loadHTML($htmlString, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

// Reset the error stack to avoid printing errors later
libxml_clear_errors();

$images = $dom->getElementsByTagName('img');

foreach ($images) {
    // Check if attributes exist before accessing them to handle optional ones
    if ($src = $image->getAttributeNS(null, 'src')) {
        if ($title = $image->getAttributeNS(null, 'title')) {
            if ($alt = $image->getAttributeNS(null, 'alt')) {
                echo "Src: {$src}\n";
                echo "Title: {$title}\n";
                echo "Alt: {$alt}\n";
                echo "---\n";
            }
        }
    }
}

This approach avoids the pitfalls of regex by leveraging a tree structure. The getAttributeNS method ensures you are accessing standard HTML attributes without worrying about namespace collisions, which rarely happen in front-end code but is good practice to know.

If you are already using Laravel, the ecosystem offers similar tools via packages like spatie/html-scraping. These packages abstract away the DOM complexity and provide a fluent interface for extracting data, which can be preferable if you prefer not to manage DOM instances manually. However, understanding the underlying DOM mechanism ensures you know what is happening under the hood when dealing with raw HTML strings or custom parsers.

Remember that this method extracts attributes from the current source string. If your goal is to list images hosted on your specific domain, ensure your scraping logic filters results based on the src attribute matching your base URL or domain root.

Our network