以下是一个使用 PHP 获取网站图标的示例代码,它会从网站的根目录中查找'favicon.ico'文件,如果找不到,就使用 Google 的 API 来获取图标:

<?php
function get_site_icon($url) {
    $cache_file = 'cache/' . md5($url) . '.ico';
    if (file_exists($cache_file)) {
        $icon_url = $cache_file;
    } else {
        $content = file_get_contents($url);
        preg_match('/<link rel='shortcut icon' href='([^']+)'/i', $content, $matches);
        if (isset($matches[1])) {
            $icon_url = $matches[1];
        } else {
            $google_url = 'https://www.google.com/s2/favicons?domain=' . $url;
            $icon_url = $google_url;
        }
        copy($icon_url, $cache_file);
    }
    return $icon_url;
}

$url = isset($_GET['url']) ? $_GET['url'] : '';
if ($url) {
    $icon_url = get_site_icon($url);
    header('Content-Type: image/x-icon');
    readfile($icon_url);
} else {
    echo 'Please specify a URL parameter.';
}
?>

该代码首先检查缓存文件夹中是否存在已下载的图标文件。如果找到缓存文件,则直接返回该文件的 URL。否则,它会尝试从页面源代码中查找'shortcut icon'标记,并使用该标记中的 URL 来下载图标文件。如果标记不存在,则使用 Google 的 API 来获取图标。最后,将下载的图标文件保存到缓存文件夹中,并返回该文件的 URL。

使用此 API 的示例 URL 为:

http://example.com/get_site_icon.php?url=www.google.com

此示例将返回 Google 的网站图标。如果您想要获取其他网站的图标,请使用相应的网站 URL 作为参数传递给该 API。

PHP 获取网站图标 API:高效、缓存、高清

原文地址: https://www.cveoy.top/t/topic/nVBf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录