10

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

 3 years ago
source link: https://www.codexworld.com/how-to/get-title-metadata-meta-tags-from-url-using-php/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Home  »  How To Guides  »  PHP   »   How to Get Title and Metadata (meta tags) from URL using PHP

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($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);

// 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

Cancel

Comment*

Your Name*

Your Email*

Your Website


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK