How to get a website's favicon with PHP?

Use the S2 service provided by google. It is as simple as this

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

Scraping this would be much easier, that trying to do it yourself.


Quick and dirty:

<?php 
$url = 'http://example.com/';
$doc = new DOMDocument();
$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 looks like http://www.getfavicon.org/?url=domain.com (FAQ) reliably scrapes a website's favicon. I realise it's a 3rd-party service but I think it's a worthy alternative to the Google favicon service.

Tags:

Php

Favicon

Regex