How to get a website's favicon with PHP?

后端 未结 13 1131
醉梦人生
醉梦人生 2020-12-02 16:08

I want to get, requested website\'s favicon with PHP. I have been recommended using Google\'s favicon service but it is not functional. I want to do something on my own but

13条回答
  •  悲哀的现实
    2020-12-02 16:30

    I've been doing something similar and I checked this with a bunch of URL and all seemed to work. URL doesn't have to be a base URL

    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 relative
            if(!isset($favicon_elems['host'])){
                $favicon = $url . '/' . $favicon;
            }
    
            return $favicon;
        }
    
        return false;
    }
    

提交回复
热议问题