How to get Title and Meta tags from URL using 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.
1 2 3 4 5 6 7 8 9 | <html> <head> <title>Welcome to our website</title> <meta name="keywords" content="this is the keywords"> <meta name="description" content="this is the description"> </head> … … </html> |
1 2 3 4 5 6 7 8 9 10 11 | <?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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <?php function file_get_contents_curl($url) { $ch = curl_init(); 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..!! 🙂