Getting title and meta tags from external website

Getting title and meta tags from external website

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

Stefan Bogdanescu

Founder & Senior Architect

Robust Title and Meta Extraction Without Simple HTML DOM Parser

Extracting <title>, <meta name="keywords">, and <meta name="description"> tags from an external URL is a common requirement for link preview generation, social sharing cards, or SEO analysis tools. While the PHP Simple HTML DOM Parser is often cited as the go-to solution for this task, it adds a significant dependency to your stack. If you prefer a lighter footprint or want to avoid the overhead of loading a full DOM parser library, you can achieve robust extraction using native PHP functions combined with cURL.

The core challenge lies in handling "invalid" or non-standard HTML. Standard regular expressions are notoriously fragile when parsing HTML because they assume well-formed tags, proper nesting, and consistent closing brackets. Real-world websites frequently deviate from these standards. A naive preg_match approach will likely fail if the target page contains unclosed tags, comments mixed with attributes, or dynamically generated content that breaks the expected pattern.

To solve this without Simple HTML DOM Parser, you must combine a reliable HTTP client with a dedicated HTML parser class that is already part of the PHP ecosystem: DOMDocument. Unlike regex, the DOM API treats HTML as a tree structure, allowing it to handle malformed markup gracefully by auto-correcting certain errors or ignoring them entirely.

Here is how you can construct a solution using cURL to fetch the content and DOMDocument to parse it. First, initialize a cURL session to retrieve the raw HTML source. It is crucial to set appropriate headers like User-Agent to prevent some servers from blocking requests, especially for sites that serve different content based on the requester.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://example.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MyApp/1.0)');
$responseHtml = curl_exec($ch);
curl_close($ch);

// If you are using Laravel or a framework, ensure the response is a string
if ($responseHtml === false) {
    return ['error' => 'Failed to fetch content'];
}

Once you have the raw HTML string, instantiate a new DOMDocument object. The key here is handling parsing errors. When loading an invalid or unusual document, DOMDocument might throw warnings that clutter your logs if not suppressed. You should set error reporting to silence these specific parser warnings while still allowing fatal errors through.

$dom = new DOMDocument();
libxml_use_internal_errors(true); // Suppress parsing warnings
$dom->loadHTML($responseHtml, LIBXML_NOENT | LIBXML_XINCLUDE);
libxml_clear_errors();

With the document loaded into memory, you can query specific nodes using XPath or standard DOM traversal methods. To extract the title, look for the <head> element and then its child <title>. For meta tags, search for elements with a name attribute matching "description" or "keywords". Note that Facebook and other platforms often use Open Graph protocol attributes (e.g., og:description) rather than standard HTML5 meta tags. While your requirement focuses on standard meta tags, it is worth noting that DOMDocument can easily handle the variation in attribute names if you adjust your XPath queries.

$title = $dom->getElementsByTagName('title')->item(0)?->nodeValue ?? null;

$metaTags = [];
foreach ($dom->getElementsByTagName('meta') as $meta) {
    $name = $meta->getAttribute('name');
    $content = $meta->getAttribute('content');
    
    if (in_array($name, ['keywords', 'description'])) {
        $metaTags[$name] = trim($content);
    }
}

This approach avoids the dependency on Simple HTML DOM Parser while providing resilience against invalid HTML. The trade-off is a slight increase in code complexity compared to a simple regex, but it offers significantly better reliability. If you find yourself needing to handle complex Open Graph tags or specific social media card requirements later, DOMDocument remains flexible enough to query those attributes as well without changing your core architecture.

For developers working within the Laravel ecosystem, this pattern integrates seamlessly into existing controllers or services. You can encapsulate this logic in a dedicated service class that accepts an URL and returns a standardized array of metadata, allowing your application to gracefully handle cases where meta tags are missing by returning null values or defaulting to user-defined fallbacks.

Our network