2011-04-26 32 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.'" /> 
相關問題