How to get a website’s favicon with PHP

A nice and simple post today.

I found myself in the need to get a website favicon dynamically with PHP.

I had hard-coded a few well known sites into my system but needed a better way. So I searched high and low across the ocean that is the Internet and found these methods.

 

One method that was found was:

<?php 
$url ='http://example.com/';
$doc =newDOMDocument();
$doc->strictErrorChecking = FALSE;
$doc->loadHTML(file_get_contents($url));
$xml = simplexml_import_dom($doc);
$arr = $xml->xpath('//link[@rel="shortcut icon"]');
echo $arr[0]['href'];
?>


It seemed a little dirty but worked.

Another ( My Fav! )

Simply, Link your image to:

http://www.google.com/s2/favicons?domain=www.yourdomain.com


Another longer method:

function getFavicon($url){# make the URL simpler
    $elems = parse_url($url);
    $url = $elems['scheme'].'://'.$elems['host'];# load site
    $output = file_get_contents($url);# look for the shortcut icon inside the loaded page
    $regex_pattern ="/rel=\"shortcut icon\" (?:href=[\'\"]([^\'\"]+)[\'\"])?/";
    preg_match_all($regex_pattern, $output, $matches);if(isset($matches[1][0])){
        $favicon = $matches[1][0];# check if absolute url or relative path
        $favicon_elems = parse_url($favicon);# if relativeif(!isset($favicon_elems['host'])){
            $favicon = $url .'/'. $favicon;}return $favicon;}returnfalse;}
 

Comments are closed.