2011-04-26 19 views
4

如何通过php检测任何网站的favicon(快捷方式图标)?如何通过php检测任何站点的favicon(快捷方式图标)?

我不能写的正则表达式,因为在不同的网站..

+1

只是解析网站的原始HTML响应..在原始字符串中寻找''link',搜索'rel =“icon”'然后在'href =“http中引用引号之间的值://example.com/myicon.png“ – 2011-04-26 12:48:29

+3

”Google图标服务“ – mario 2011-04-26 12:54:46

+0

我们是否可以接受? – 2011-06-02 14:15:04

回答

14

您可以使用此地址并放到一个正则表达式这个

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

这解决您的正则表达式和每个域

+0

+1,哇,好戏! – 2011-04-26 13:08:18

+0

从来没有见过,以前,很好:) – Simon 2011-04-26 13:19:41

+0

为什么自己的工作,当谷歌已经完成它;) – 2011-08-11 07:55:22

1

您可以要求http://domain.com/favicon.ico PHP和看看你得到一个404

如果你得到一个404那里,你可以通过网站的DOM ,寻找head元素中link元素与rel="icon"中引用的不同位置。

// Helper function to see if a url returns `200 OK`. 
function $resourceExists($url) { 
    $headers = get_headers($request); 
    if (! $headers) { 
     return FALSE; 
    } 
    return (strpos($headers[0], '200') !== FALSE); 
} 

function domainHasFavicon($domain) { 
    // In case they pass 'http://example.com/'. 
    $request = rtrim($domain, '/') . '/favicon.ico'; 

    // Check if the favicon.ico is where it usually is. 
    if (resourceExists($request)) {   
     return TRUE; 
    } else { 
     // If not, we'll parse the DOM and find it 
     $dom = new DOMDocument; 
     $dom->loadHTML($domain); 
     // Get all `link` elements that are children of `head` 
     $linkElements = $dom 
         ->getElementsByTagName('head') 
         ->item(0) 
         ->getElementsByTagName('link'); 

     foreach($linkElements as $element) { 
      if (! $element->hasAttribute('rel')) { 
       continue; 
      } 
      // Split the rel up on whitespace separated because it can have `shortcut icon`. 
      $rel = preg_split('/\s+/', $element->getAttribute('rel')); 

      if (in_array('link', $rel)) { 
       $href = $element->getAttribute('href'); 

       // This may be a relative URL. 
       // Let's assume http, port 80 and Apache 
       $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; 

       if (substr($href, 0, strlen($url)) !== $url) { 
        $href = $url . $href; 
       } 

       return resourceExists($href); 
     } 
    } 
    return FALSE; 
} 

如果你想要的网址回到favicon.ico,这是微不足道的修改上面的功能。

1
$address = 'http://www.youtube.com/' 
$domain = parse_url($address, PHP_URL_HOST); 

或从数据库中不同的结果有问题

$domain = parse_url($row['address_column'], PHP_URL_HOST); 

display with

<image src="http://www.google.com/s2/favicons?domain='.$domain.'" /> 
相关问题