Read meta description and title tag of a web page using PHP

By Faruque Ahamed Mollick

Meta description and title tag are two important SEO parameter of any type of site. Every web page that needs to be rank better on search engines, must have meta description tag and title tag. Search engines like Google, Bing, YaHoo give the most value to these two SEO parameters.

Below is a given example which shows you how meta description tag looks like:

<meta name="description" content="Content for meta description tag"/>

And the title tag looks like below example:

<title>Content for title tag</title>

 How to read the meta description and title tag of a web page content using PHP?

Now I am going to tell you the way of reading meta description and title tag using the popular web development language PHP. Several times it may be needed to get the meta description and title tag content.

Getting title tag means you have to get the text content between <title> and </title>. And getting meta tag content means getting the content that you can see inside quotation like content=”meta description content”.



Reading meta description using PHP

Below is the given PHP code snippet to read the meta description tag:

<?php
$meta_tags = get_meta_tags('http://www.example.com/page');
echo $meta_tags['description'];
?>

If you run the above code snippet, then it will display meta description text content from the page www.example.com/page. Now below is the modified code of the above code snippet to check if meta description exists on the web page or not using PHP if condition:

<?php
$meta_tags = get_meta_tags('http://www.example.com/page');
if (isset($meta_tags['description'])) {
echo $meta_tags['description'];
}
else {
echo "Meta description not exists";
}
?>

Get title tag content text using PHP

The PHP code to read title tag is given below:

<?php
  function get_title($url) {
        $fp = file_get_contents($url);
        if (!$fp) 
            return null;
        $res = preg_match("/<title>(.*)<\/title>/siU", $fp, $title_matches);
        if (!$res) 
            return null; 
        $title = preg_replace('/\s+/', ' ', $title_matches[1]);
        $title = trim($title);
        return $title;
    }
echo get_title("http://www.example.com/page");
?>

Now if you run the above code on your server then you will get the title tag content text as the response. It will display title content for the web page www.example.com/page.

Leave a Reply

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