How to Get Title and Metadata (meta tags) from URL using PHP

HTML meta tags are used to provide structured metadata about an HTML document. The metadata is defined in the <meta> tag. The <meta> tags are added always inside the <head> element. Mostly, 3 meta elements are used to specify the metadata for the web page, title, description, and keywords. The information from the meta tags can be fetched using PHP.

The following example code snippets show you how to get the title and meta tags from an external URL using PHP.

<?php 

// Web page URL
$url 'https://www.codexworld.com/';

// Extract HTML using curl
$ch curl_init();
curl_setopt($chCURLOPT_HEADER0);
curl_setopt($chCURLOPT_RETURNTRANSFER1);
curl_setopt($chCURLOPT_URL$url);
curl_setopt($chCURLOPT_FOLLOWLOCATION1);

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

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

// Parse DOM to get Title data
$nodes $dom->getElementsByTagName('title');
$title $nodes->item(0)->nodeValue;

// Parse DOM to get meta data
$metas $dom->getElementsByTagName('meta');

$description $keywords '';
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/>';
echo 
"Description: $description"'<br/>';
echo 
"Keywords: $keywords";

?>

Leave a reply

keyboard_double_arrow_up