如何获得一个网站';是用PHP的favicon吗?

如何获得一个网站';是用PHP的favicon吗?,php,regex,favicon,Php,Regex,Favicon,我想得到,请求网站的PHP的favicon。有人建议我使用谷歌的favicon服务,但它不起作用。我想自己做点什么,但不知道正则表达式的用法 我在谷歌上发现了一个在大多数情况下都有效的类,但它的错误率是不可接受的。您可以在这里查看: 有人能帮我用正则表达式获取favicon吗?如果你想从特定网站检索favicon,你只需要从他们网站的根目录中获取favicon.ico。像这样: $domain = "www.example.com"; $url = "http://".$domain."/fav

我想得到,请求网站的PHP的favicon。有人建议我使用谷歌的favicon服务,但它不起作用。我想自己做点什么,但不知道正则表达式的用法

我在谷歌上发现了一个在大多数情况下都有效的类,但它的错误率是不可接受的。您可以在这里查看:


有人能帮我用正则表达式获取favicon吗?

如果你想从特定网站检索favicon,你只需要从他们网站的根目录中获取
favicon.ico
。像这样:

$domain = "www.example.com";
$url = "http://".$domain."/favicon.ico";
$icondata = file_get_contents($url);

... you can now do what you like with the icon data
据介绍,有两种主要的方法可供网站使用,让浏览器获取favicon。第一个是Steve提到的,在Web服务器的根目录中,图标存储为favicon.ico。第二个是通过HTML链接标记引用favicon


为了涵盖所有这些情况,最好的办法是首先测试favicon.ico文件是否存在,如果不存在,则搜索看起来像
http://www.getfavicon.org/?url=domain.com
()可靠地刮取网站的favicon。我意识到这是一项第三方服务,但我认为它是谷歌favicon服务的一个有价值的替代方案。

快速而肮脏:

<?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'];
xpath('//link[@rel=“快捷方式图标”]”);
echo$arr[0]['href'];

使用谷歌提供的
S2服务。就这么简单

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

如果你想自己动手的话,这会容易得多。

我自己已经实现了一个favicon抓取器,我在另一篇StackOverflow文章中详细介绍了它的用法:


谢谢,如果有帮助请告诉我。另外,我们非常感谢您的反馈。

我也做了类似的事情,我用一堆URL检查了一下,所有这些似乎都很有效URL不必是基本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;
}

第一种方法,我们可以从fevicon.ico中搜索它,如果找到,它将显示出来,否则不会

<?php
        $userPath=$_POST["url"];
        $path="http://www.".$userPath."/favicon.ico";
        $header=  get_headers($path);
        if(preg_match("|200|", $header[0]))
        {
            echo '<img src="'.$path.'">';
        }
        else
        {
            echo "<span class=error>Not found</span>";
        }
    ?>

在另一种方法中,您可以搜索图标并获取该图标文件

    <?php
$website=$_POST["url"];
$fevicon= getFavicon($website);
echo '<img src="http://www.'.$website.'/'.$fevicon.'">';
function getFavicon($site)
{
            $html=file_get_contents("http://www.".$site);
            $dom=new DOMDocument();
            @$dom->loadHTML($html);
            $links=$dom->getElementsByTagName('link');
            $fevicon='';

            for($i=0;$i < $links->length;$i++ )
            {
                $link=$links->item($i);
                if($link->getAttribute('rel')=='icon'||$link->getAttribute('rel')=="Shortcut Icon"||$link->getAttribute('rel')=="shortcut icon")
                {
                    $fevicon=$link->getAttribute('href');
                }
            }
            return  $fevicon;
}
?>

找到此线程。。。我已经写了一个WordPress插件,它包含了很多关于检索favicon的变体。因为有很多GPL代码:

它允许您运行一个服务器,您可以通过xml rpc请求从该服务器请求图标,以便任何客户端都可以请求图标。它有一个插件结构,所以你可以尝试谷歌,getfavicon等。。。看看这些服务中是否有一项提供了什么。如果没有,那么它将进入一个图标获取模式,考虑所有http状态(301/302/404),并尽可能在任何地方找到图标。在此之后,它使用图像库函数在文件内部检查它是否真的是图像以及图像的类型(有时扩展名是错误的),并且它是可插入的,因此您可以在图像转换后添加图像库函数或管道中的额外功能

http抓取文件围绕我在上面看到的内容执行一些逻辑:

但这只是管道的一部分

一旦你深入研究,就会变得相当复杂。

请看以下答案:。这是一个易于使用的PHP类,用于获取favicon URL并下载它,它还提供了有关类似favicon的文件类型或如何找到favicon的一些信息(默认URL,
标记…):


$url='1!'http://thamaraiselvam.strikingly.com/';
$doc=新的DOMDocument();
$doc->strigerrorchecking=FALSE;
@$doc->loadHTML(文件获取内容($url));
$xml=simplexml\u import\u dom($doc);
$arr=$xml->xpath('//link[@rel=“快捷方式图标”]');
如果(!empty($arr[0]['href'])){
回声“;
}
其他的
回声“;
我做了一些修改,添加了一个,看起来是这样的:

<?php
        $website=$_GET['u'];
        $fevicon= getFavicon($website);
        echo '<img src="'.path_to_absolute($fevicon,$website).'"></img>';

            function getFavicon($site)
            {
            $html=file_get_contents($site);
            $dom=new DOMDocument();
            @$dom->loadHTML($html);
            $links=$dom->getElementsByTagName('link');
            $fevicon='';

            for($i=0;$i < $links->length;$i++ )
            {
                $link=$links->item($i);
                if($link->getAttribute('rel')=='icon'||$link->getAttribute('rel')=="Shortcut Icon"||$link->getAttribute('rel')=="shortcut icon")
                {
                    $fevicon=$link->getAttribute('href');
                }
            }
            return  $fevicon;
            }

    // transform to absolute path function... 
    function path_to_absolute($rel, $base)
    {
    /* return if already absolute URL */
    if (parse_url($rel, PHP_URL_SCHEME) != '') return $rel;
    /* queries and anchors */
    if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;
    /* parse base URL and convert to local variables:
       $scheme, $host, $path */
    extract(parse_url($base));
    /* remove non-directory element from path */
    $path = preg_replace('#/[^/]*$#', '', $path);
    /* destroy path if relative url points to root */
    if ($rel[0] == '/') $path = '';
    /* dirty absolute URL */
    $abs = "$host$path/$rel";
    /* replace '//' or '/./' or '/foo/../' with '/' */
    $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
    for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
    /* absolute URL is ready! */
    return $scheme.'://'.$abs;
    }

?>

当然可以用
https://www.domain.tld/favicon/this_script.php?u=http://www.example.com
仍然无法捕获所有选项,但现在绝对路径已解决。希望有帮助。

PHP抓取Favicon 这是一种使用许多参数从页面URL获取favicon的舒适方法

工作原理
  • 检查favicon是否已存在本地或不希望保存,如果存在,则返回路径和文件名
  • 否则请加载URL并尝试将favicon位置与regex匹配
  • 如果我们有匹配,favicon链接将成为绝对链接
  • 如果我们没有favicon,我们会尝试在域根中获取一个
  • 如果仍然没有favicon,我们将随机尝试google、faviconkit和favicongrabber API
  • 如果应该保存favicon,请尝试加载favicon URL
  • 如果愿意,保存Favicon以备下次使用,并返回路径和文件名
  • 因此,它结合了两种方式:尝试从页面获取Favicon,如果这不起作用,则使用“API”服务返回Favicon;-)


    为什么要使用PHP??它可以用HTMLWhat's's would with?@diecho我必须用Php,因为我会在学习favicon路径后保存url。@vooD whynot?我还能做什么?@Marcel,因为我认为它只能获得domain/favicon.ico或domain/favicon.png,但我需要所有。这不包括favicon。我知道,但不是每个网站都使用该路径。例如,我从来没有用过这种方法。favicon不需要在根上。而且我认为它甚至不需要再被称为favicon.ico了。没关系,但我如何获得该值呢?url包含在href属性中。如何提取url将取决于您选择使用正则表达式还是字符串搜索。如果您选择使用正则表达式,您可以创建一个特定的表达式,该表达式将为您提供标签的href属性中的路径。如果使用字符串搜索,可以从找到的位置继续搜索,直到找到href属性并提取url。谢谢mdec,但我的主要问题是不知道如何在整个页面脚本中获取它。如果我没有误解的话,你是在告诉我“从脚本中抓取它”:)哇,这通过了所有的查找。谢谢。我遇到的另一个类似于Google favicon的服务,它只是将
    favicon.ico
    转换成PNG。谢谢,再见
    $url = 'http://thamaraiselvam.strikingly.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"]');
    if (!empty($arr[0]['href'])) {
        echo "<img src=".$arr[0]['href'].">";
     }
    else 
    echo "<img src='".$url."/favicon.ico'>";
    
    <?php
            $website=$_GET['u'];
            $fevicon= getFavicon($website);
            echo '<img src="'.path_to_absolute($fevicon,$website).'"></img>';
    
                function getFavicon($site)
                {
                $html=file_get_contents($site);
                $dom=new DOMDocument();
                @$dom->loadHTML($html);
                $links=$dom->getElementsByTagName('link');
                $fevicon='';
    
                for($i=0;$i < $links->length;$i++ )
                {
                    $link=$links->item($i);
                    if($link->getAttribute('rel')=='icon'||$link->getAttribute('rel')=="Shortcut Icon"||$link->getAttribute('rel')=="shortcut icon")
                    {
                        $fevicon=$link->getAttribute('href');
                    }
                }
                return  $fevicon;
                }
    
        // transform to absolute path function... 
        function path_to_absolute($rel, $base)
        {
        /* return if already absolute URL */
        if (parse_url($rel, PHP_URL_SCHEME) != '') return $rel;
        /* queries and anchors */
        if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;
        /* parse base URL and convert to local variables:
           $scheme, $host, $path */
        extract(parse_url($base));
        /* remove non-directory element from path */
        $path = preg_replace('#/[^/]*$#', '', $path);
        /* destroy path if relative url points to root */
        if ($rel[0] == '/') $path = '';
        /* dirty absolute URL */
        $abs = "$host$path/$rel";
        /* replace '//' or '/./' or '/foo/../' with '/' */
        $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
        for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
        /* absolute URL is ready! */
        return $scheme.'://'.$abs;
        }
    
    ?>
    
    <?php
    /*
    
    PHP Grab Favicon
    ================
    
    > This `PHP Favicon Grabber` use a given url, save a copy (if wished) and return the image path.
    
    How it Works
    ------------
    
    1. Check if the favicon already exists local or no save is wished, if so return path & filename
    2. Else load URL and try to match the favicon location with regex
    3. If we have a match the favicon link will be made absolute
    4. If we have no favicon we try to get one in domain root
    5. If there is still no favicon we randomly try google, faviconkit & favicongrabber API
    6. If favicon should be saved try to load the favicon URL
    7. If wished save the Favicon for the next time and return the path & filename
    
    How to Use
    ----------
    
    ```PHP
    $url = 'example.com';
    
    $grap_favicon = array(
    'URL' => $url,   // URL of the Page we like to get the Favicon from
    'SAVE'=> true,   // Save Favicon copy local (true) or return only favicon url (false)
    'DIR' => './',   // Local Dir the copy of the Favicon should be saved
    'TRY' => true,   // Try to get the Favicon frome the page (true) or only use the APIs (false)
    'DEV' => null,   // Give all Debug-Messages ('debug') or only make the work (null)
    );
    
    echo '<img src="'.grap_favicon($grap_favicon).'">';
    ```
    
    Todo
    ----
    Optional split the download dir into several sub-dirs (MD5 segment of filename e.g. /af/cd/example.com.png) if there are a lot of favicons.
    
    Infos about Favicon
    -------------------
    https://github.com/audreyr/favicon-cheat-sheet
    
    ###### Copyright 2019 Igor Gaffling
    
    */ 
    
    $testURLs = array(
      'http://aws.amazon.com',
      'http://www.apple.com',
      'http://www.dribbble.com',
      'http://www.github.com',
      'http://www.intercom.com',
      'http://www.indiehackers.com',
      'http://www.medium.com',
      'http://www.mailchimp.com',
      'http://www.netflix.com',
      'http://www.producthunt.com',
      'http://www.reddit.com',
      'http://www.slack.com',
      'http://www.soundcloud.com',
      'http://www.stackoverflow.com',
      'http://www.techcrunch.com',
      'http://www.trello.com',
      'http://www.vimeo.com',
      'https://www.whatsapp.com/',
      'https://www.gaffling.com/',
    );
    
    foreach ($testURLs as $url) {
      $grap_favicon = array(
        'URL' => $url,   // URL of the Page we like to get the Favicon from
        'SAVE'=> true,   // Save Favicon copy local (true) or return only favicon url (false)
        'DIR' => './',   // Local Dir the copy of the Favicon should be saved
        'TRY' => true,   // Try to get the Favicon frome the page (true) or only use the APIs (false)
        'DEV' => null,   // Give all Debug-Messages ('debug') or only make the work (null)
      );
      $favicons[] = grap_favicon($grap_favicon);
    }
    foreach ($favicons as $favicon) {
      echo '<img title="'.$favicon.'" style="width:32px;padding-right:32px;" src="'.$favicon.'">';
    }
    echo '<br><br><tt>Runtime: '.round((microtime(true)-$_SERVER["REQUEST_TIME_FLOAT"]),2).' Sec.';
    
    function grap_favicon( $options=array() ) {
    
      // Ini Vars
      $url       = (isset($options['URL']))?$options['URL']:'gaffling.com';
      $save      = (isset($options['SAVE']))?$options['SAVE']:true;
      $directory = (isset($options['DIR']))?$options['DIR']:'./';
      $trySelf   = (isset($options['TRY']))?$options['TRY']:true;
      $DEBUG     = (isset($options['DEV']))?$options['DEV']:null;
    
      // URL to lower case
        $url = strtolower($url);
    
        // Get the Domain from the URL
      $domain = parse_url($url, PHP_URL_HOST);
    
      // Check Domain
      $domainParts = explode('.', $domain);
      if(count($domainParts) == 3 and $domainParts[0]!='www') {
        // With Subdomain (if not www)
        $domain = $domainParts[0].'.'.
                  $domainParts[count($domainParts)-2].'.'.$domainParts[count($domainParts)-1];
      } else if (count($domainParts) >= 2) {
        // Without Subdomain
            $domain = $domainParts[count($domainParts)-2].'.'.$domainParts[count($domainParts)-1];
        } else {
          // Without http(s)
          $domain = $url;
        }
    
        // FOR DEBUG ONLY
        if($DEBUG=='debug')print('<b style="color:red;">Domain</b> #'.@$domain.'#<br>');
    
        // Make Path & Filename
        $filePath = preg_replace('#\/\/#', '/', $directory.'/'.$domain.'.png');
    
        // If Favicon not already exists local
      if ( !file_exists($filePath) or @filesize($filePath)==0 ) {
    
        // If $trySelf == TRUE ONLY USE APIs
        if ( isset($trySelf) and $trySelf == TRUE ) {  
    
          // Load Page
          $html = load($url, $DEBUG);
    
          // Find Favicon with RegEx
          $regExPattern = '/((<link[^>]+rel=.(icon|shortcut icon|alternate icon)[^>]+>))/i';
          if ( @preg_match($regExPattern, $html, $matchTag) ) {
            $regExPattern = '/href=(\'|\")(.*?)\1/i';
            if ( isset($matchTag[1]) and @preg_match($regExPattern, $matchTag[1], $matchUrl)) {
              if ( isset($matchUrl[2]) ) {
                
                // Build Favicon Link
                $favicon = rel2abs(trim($matchUrl[2]), 'http://'.$domain.'/');
                
                // FOR DEBUG ONLY
                if($DEBUG=='debug')print('<b style="color:red;">Match</b> #'.@$favicon.'#<br>');
    
              }
            }
          }
          
          // If there is no Match: Try if there is a Favicon in the Root of the Domain
            if ( empty($favicon) ) { 
            $favicon = 'http://'.$domain.'/favicon.ico';
    
            // Try to Load Favicon
            if ( !@getimagesize($favicon) ) {
              unset($favicon);
            }
            }
    
        } // END If $trySelf == TRUE ONLY USE APIs
            
        // If nothink works: Get the Favicon from API
        if ( !isset($favicon) or empty($favicon) ) {
    
          // Select API by Random
          $random = rand(1,3);
    
          // Faviconkit API
          if ($random == 1 or empty($favicon)) {
            $favicon = 'https://api.faviconkit.com/'.$domain.'/16';
          }
    
          // Favicongrabber API
          if ($random == 2 or empty($favicon)) {
            $echo = json_decode(load('http://favicongrabber.com/api/grab/'.$domain,FALSE),TRUE);
            
            // Get Favicon URL from Array out of json data (@ if something went wrong)
            $favicon = @$echo['icons']['0']['src'];
    
          }
    
          // Google API (check also md5() later)
          if ($random == 3) {
            $favicon = 'http://www.google.com/s2/favicons?domain='.$domain;
          } 
          
          // FOR DEBUG ONLY
          if($DEBUG=='debug')print('<b style="color:red;">'.$random.'. API</b> #'.@$favicon.'#<br>');
    
        } // END If nothink works: Get the Favicon from API
    
        // Write Favicon local
        $filePath = preg_replace('#\/\/#', '/', $directory.'/'.$domain.'.png');
    
        // If Favicon should be saved
        if ( isset($save) and $save == TRUE ) {
          
          //  Load Favicon
          $content = load($favicon, $DEBUG);
    
          // If Google API don't know and deliver a default Favicon (World)
          if ( isset($random) and $random == 3 and 
               md5($content) == '3ca64f83fdcf25135d87e08af65e68c9' ) {
            $domain = 'default'; // so we don't save a default icon for every domain again
    
            // FOR DEBUG ONLY
            if($DEBUG=='debug')print('<b style="color:red;">Google</b> #use default icon#<br>');
            
          }
    
          // Write 
          $fh = @fopen($filePath, 'wb');
          fwrite($fh, $content);
          fclose($fh);
    
          // FOR DEBUG ONLY
            if($DEBUG=='debug')print('<b style="color:red;">Write-File</b> #'.@$filePath.'#<br>');
    
        } else {
          
          // Don't save Favicon local, only return Favicon URL
          $filePath = $favicon;
        }
    
        } // END If Favicon not already exists local
    
        // FOR DEBUG ONLY
        if ($DEBUG=='debug') {
    
        // Load the Favicon from local file
          if ( !function_exists('file_get_contents') ) {
          $fh = @fopen($filePath, 'r');
          while (!feof($fh)) {
            $content .= fread($fh, 128); // Because filesize() will not work on URLS?
          }
          fclose($fh);
        } else {
          $content = file_get_contents($filePath);
        }
          print('<b style="color:red;">Image</b> <img style="width:32px;" 
                 src="data:image/png;base64,'.base64_encode($content).'"><hr size="1">');
      }
    
      // Return Favicon Url
      return $filePath;
    
    } // END MAIN Function
    
    /* HELPER load use curl or file_get_contents (both with user_agent) and fopen/fread as fallback */
    function load($url, $DEBUG) {
      if ( function_exists('curl_version') ) {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_USERAGENT, 'FaviconBot/1.0 (+http://'.$_SERVER['SERVER_NAME'].'/');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        $content = curl_exec($ch);
        if ( $DEBUG=='debug' ) { // FOR DEBUG ONLY
          $http_code = curl_getinfo($ch);
          print('<b style="color:red;">cURL</b> #'.$http_code['http_code'].'#<br>');
        }
        curl_close($ch);
        unset($ch);
      } else {
        $context = array ( 'http' => array (
            'user_agent' => 'FaviconBot/1.0 (+http://'.$_SERVER['SERVER_NAME'].'/)'),
        );
        $context = stream_context_create($context);
          if ( !function_exists('file_get_contents') ) {
          $fh = fopen($url, 'r', FALSE, $context);
          $content = '';
          while (!feof($fh)) {
            $content .= fread($fh, 128); // Because filesize() will not work on URLS?
          }
          fclose($fh);
        } else {
          $content = file_get_contents($url, NULL, $context);
        }
      }
      return $content;
    }
    
    /* HELPER: Change URL from relative to absolute */
    function rel2abs( $rel, $base ) {
        extract( parse_url( $base ) );
        if ( strpos( $rel,"//" ) === 0 ) return $scheme . ':' . $rel;
        if ( parse_url( $rel, PHP_URL_SCHEME ) != '' ) return $rel;
        if ( $rel[0] == '#' or $rel[0] == '?' ) return $base . $rel;
        $path = preg_replace( '#/[^/]*$#', '', $path);
        if ( $rel[0] ==  '/' ) $path = '';
        $abs = $host . $path . "/" . $rel;
        $abs = preg_replace( "/(\/\.?\/)/", "/", $abs);
        $abs = preg_replace( "/\/(?!\.\.)[^\/]+\/\.\.\//", "/", $abs);
        return $scheme . '://' . $abs;
    }