PHP: How to get meta tags from a webpage

A simple php function which help you fetch meta tags from a webpage. We will use get_meta_tags function:

$tags = get_meta_tags('http://www.example.com/'); 
echo $tags['author']; // Meta author name 
echo $tags['keywords']; // Meta keywords 
echo $tags['description']; // Meta Description 
echo $tags['geo_position']; // Meta geo Position

And to avoid 404 header response code, you can add an additional function to check header code:

$url = 'http://www.example.com/'; 
$curl = curl_init(); 
curl_setopt_array( $curl, array( CURLOPT_RETURNTRANSFER => true, CURLOPT_URL => $url ) ); 
curl_exec( $curl ); 
$response_code = curl_getinfo( $curl, CURLINFO_HTTP_CODE ); 
//$response_code is header response status curl_close( $curl ); 

if ($response_code != '404') { 
    $tags = get_meta_tags($url); 
    echo $tags['author']; // Meta author name 
    echo $tags['keywords']; // Meta keywords 
    echo $tags['description']; // Meta Description 
    echo $tags['geo_position']; // Meta geo Position 
}

An another way, we can use get_headers

$url = 'http://www.example.com/'; 
$headers = array(); 
$metatags = array(); 
$validhost = filter_var(gethostbyname(parse_url($url,PHP_URL_HOST)),FILTER_VALIDATE_IP); 
if($validhost){ 
    // get headers only when Domain is valid 
    $headers = get_headers($url, 1); 
    if(substr($headers[0], 9, 3) == '200') { 
        // read Metatags only when Statuscode OK 
        $metatags = get_meta_tags($url); 
        echo $tags['author']; // Meta author name 
        echo $tags['keywords']; // Meta keywords 
        echo $tags['description']; // Meta Description 
        echo $tags['geo_position']; // Meta geo Position 
    } 
}

Written on 10 June 2012

Share your thoughts