Get meta tags of a web page in PHP

In this article, I am going to show you how to extract all meta tags of a web page in PHP. After we get meta tags of a web page, we are going to get the specific meta content by its name.

Before going forward, let me talk a little bit about meta tags of a web page.

A meta tag of a web page looks like you can see below:

<meta name="distribution" content="This is the content of our meta tag" />

From the above meta tag example, you can see that a meta tag consists of name and content in general. A page may have multiple meta tags.

 

Extracts all meta tags in PHP

Extracting all meta tags is an easy task in PHP as there is a built-in function available. The get_meta_tags() function in PHP will able to extract all meta tags from a given URL. All you need is just to pass the URL as a parameter.

In our example, we are going to use “https://www.domain.com/” to retrieve the meta tags. Let’s see our code below:




<?php
$url = "https://www.domain.com/";
$metas = get_meta_tags($url);
echo "<pre>"; print_r($metas); echo "</pre>";
?>

Quite simple, isn’t it? Yes, the above two lines of code are enough to extract all the meta tags of a web page. The last line is for printing the result on the web page. If we run our code, then it will print an array that contains all the meta tags.

 

Get specific meta tag value

Now we can get any specific meta tag value by its name just like you can see below:

<?php
$description = $metas['description'];
$keywords = $metas['keywords'];
$rating = $metas['rating'];
?>

So what we did in the above code actually?

The meta tags name in our array is actually the index which contains the value of meta tags. So we are just picking the value by the index or you can say by the meta name.

 

Also, read:

 

So from this article, we have learned how to get meta tags of a web page in PHP as well as how to get the value of a specific meta tag by its name.


Leave a Reply

Your email address will not be published. Required fields are marked *