如何检查 css 文件是否缩小或不使用 php



我正在创建一个SEO分析器,它将检查CSS和js文件是否被缩小。HTML解析器将从网站中提取CSS和js文件的URL。

如何检查该 CSS/js 文件是否被缩小或未使用 PHP?

CSS 文件的 URL 可以是这样的:

http://fonts.googleapis.com/css?family=Dosis:200,300,400,500,600,700,800
http://www.inforge.in/css/style.css
这是一个

PHP函数,可以通过网站解析并找到有多少本地CSS文件未缩小。这比你要求的要多一点,但应该可以帮助你。

<?php
/**
 * Find the number of unminified CSS files on a website
 * @param  string  $url            The root URL of the website to test
 * @param  integer $lines_per_file What's the max number of lines a minified CSS file should have?
 * @return integer                 Number of CSS files on a website that aren't minified
 */
function how_many_unminified_css_files( $url, $lines_per_file = 3 )
    $unminimized_css_files = 0;
    // Get the website's HTML
    $html = file_get_contents( $url );
    // Find all local css files
    preg_match( "/({$url}.*.css)/gi", $html, $css_files );
    // Remove the global match that preg_match returns
    array_shift( $css_files );
    // Loop through all the local CSS files
    // And count how many lines they have
    foreach( $css_files as $css_file ) {
        $linecount = 0;
        // "Open" the CSS file
        $handle = fopen($css_file, "r");
        // Count the number of lines
        while(!feof($handle)){
          $line = fgets($handle);
          $linecount++;
        }
        // Close the CSS file
        fclose($handle);
        // If the CSS file has more lines than we deem appropriate, 
        // we'll consider it not minified
        if ( $linecount > $lines_per_file ) {
            $unminimized_css_files++;
        }
    }
    // Return the number of files that we don't think are minified
    return $unminimized_css_files;
}

试试这个:

function is_mini($fileName){
  $f = @fopen($fileName, 'r'); $l = strlen(file_get_contents($fileName));
  if(strlen(fgets($f, $l)) === $l){
    return true;
  }
  return false;
}

它根据$fileName打开一个文件进行读取,因此'r',然后根据fgets()返回的单行测试文件的strlen()。所以它真的只是确保它是一行代码。

最新更新