php |
How to get Title and Meta tags from URL using PHP
There are 2 ways to get Meta Tags in PHP 1. get_meta_tags() function 2. Using cURL
Get Meta tags using in-built function
Using the get_meta_tags() function we can extract the meta tags from the webpage. We need to pass the url in this function. This function returns the all <meta> tags until the closing </head> tag.
function GetMetaTag(){
$meta_tags = get_meta_tags('https://tagstack.org/');
print_r($meta_tags);
}
Get Title and Meta tags using cURL
function GetMetaTagCURL(){
$url = "https://tagstack.org/";
$html = file_get_contents_curl($url);
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
$title = $nodes->item(0)->nodeValue;
$metas = $doc->getElementsByTagName('meta');
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". '
';
echo "Description: $description". '
';
echo "Keywords: $keywords";
}
function file_get_contents_curl($url)
{
$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);
return $data;
}