PHP:获取HTML网页的所有CSS文件


PHP: Get all CSS files of an HTML web page

我正在尝试从URL获取html文件的所有CSS文件。

我知道,如果我想获取HTML代码,这很容易 - 只需使用PHP函数 - file_get_contents

问题是 - 如果我可以轻松地在 HTML 的 URL 中搜索并从那里获取所有相关 CSS 文件的文件或内容?

注意 - 我想构建一个引擎来获取大量 CSS 文件,这就是为什么仅仅阅读源代码是不够的。

谢谢

您可以尝试使用 http://simplehtmldom.sourceforge.net/进行 HTML 解析。

require_once 'SimpleHtmlDom/simple_html_dom.php';
$url = 'www.website-to-scan.com';
$website = file_get_html($url);
// You might need to tweak the selector based on the website you are scanning
// Example: some websites don't set the rel attribute
// others might use less instead of css
//
// Some other options:
// link[href] - Any link with a href attribute (might get favicons and other resources but should catch all the css files)
// link[href="*.css*"] - Might miss files that aren't .css extension but return valid css (e.g.: .less, .php, etc)
// link[type="text/css"] - Might miss stylesheets without this attribute set
foreach ($website->find('link[rel="stylesheet"]') as $stylesheet)
{
    $stylesheet_url = $stylesheet->href;
    // Do something with the URL
}

您需要解析 HTML 标记以查找 CSS 文件。例如,您可以使用preg_match来做到这一点 - 寻找匹配的正则表达式。

可以找到此类文件的正则表达式可能是这样的:

'<link .+href="'..+css.+"'>