Clue Mediator

How to get Title and Meta tags from URL using PHP

📅July 5, 2021
🗁PHP

Today we’ll explain to you how to get Title and Meta tags from URL using PHP.

Checkout more articles on PHP

Get Meta tags using in-built function

Using the `get_meta_tags()` function we can extract the meta tags from the webpage. We need to pass the url in this function. This function returns the all `<meta>` tags until the closing `</head>` tag.

Let’s take an example for better understanding. Suppose we have an HTML head section as shown below.

index.html



<title>Welcome to our website</title>
<meta name="keywords" content="this is the keywords">
<meta name="description" content="this is the description">

…
…

index.php

<!--?php
$meta_tags = get_meta_tags('http://www.example.com/');
print_r($tags);
?-->

// Output:
Array
(
    [keywords] => this is the keywords
    [description] => this is the description
)

Get Title and Meta tags using cURL

In the above function, we can only get the meta tags using the `get_meta_tags()` function but can’t get the `<title>` tag. So now we will show you how to get the title and meta tags using cURL in PHP.

<!--?php
function file_get_contents_curl($url)
{
    $ch = curl_init();<p-->

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

$url = "'http://www.example.com/code";

$html = file_get_contents_curl($url);

// Load HTML to DOM object
$doc = new DOMDocument();
@$doc->loadHTML($html);

// Parse DOM to get Title data

$nodes = $doc->getElementsByTagName('title');
$title = $nodes->item(0)->nodeValue;

// Parse DOM to get metadata
$metas = $doc->getElementsByTagName('meta');

for ($i = 0; $i < $metas->length; $i++)
{
    $meta = $metas->item($i);
    if($meta->getAttribute('name') == 'description')
        $description = $meta->getAttribute('content');
    if($meta->getAttribute('name') == 'keywords')
        $keywords = $meta->getAttribute('content');
}

echo "Title: $title". '<br><br>';
echo "Description: $description". '<br><br>';
echo "Keywords: $keywords";
?>

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂