How to Get Webpage Title and Meta Description from URL in PHP

multiple XML sitemap Get Webpage Title Textbox Dynamically crawl password protecteed PHP Interview Questions

Now see How to Get Webpage Title and Meta Description from URL in PHP. You may need some third-party DOM Parser for this sort of task but PHP is uber-smart and provides you with some fast native solutions. Retrieving page title and meta description tags from url is lot easier than you think. Here we’ll see how to do it.

A Web Page title can be found between the <title> and </title> tag and description within <meta> tag. Page title is self-explanatory and meta tags store various useful information about a webpage like title, description, keywords, author etc.

Also Read :How to Convert Data from mysql to json using php

Here is method for Get Webpage Title and Meta Description from URL in PHP:

In order to get/retrieve web page title from url, you have to use function file_get_contents() and regular expression together. Here is the php function to retrieve the contents found between <title> </title> tag.

// function to get webpage title
function getTitle($url) {
    $page = file_get_contents($url);
    $title = preg_match('/<title[^>]*>(.*?)<\/title>/ims', $page, $match) ? $match[1] : null;
    return $title;
// get web page title
echo 'Title: ' . getTitle('');

// Output:
// Title: PHP 5 Tutorial

PHP Code to Get Webpage Meta Description from URL:

Get/Retrieve meta description from webpage is even more easier with php’s native get_meta_tags() method. The function get_meta_tags() extracts all the meta tag content attributes from any file/url and returns it as an array.

Here is the php function to get the meta description from url.

// function to get meta description
function getDescription($url) {
    $tags = get_meta_tags($url);
    return @($tags['description'] ? $tags['description'] : "NULL");
// get web page meta description
echo 'Meta Description: ' . getDescription('');

// Output:
// Meta Description: Well organized and easy to understand Web bulding tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, and XML. 

Some WebPages may miss meta tags and the above function will return null value if it is not present.

Also you can retrieve the rest of the meta tags in the same way.

echo $tags['keywords'];
echo $tags['author'];

Leave a Reply