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

时间:2016-02-01 03:11:56

标签: javascript php html css minify

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

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

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

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

2 个答案:

答案 0 :(得分:1)

试试这个:

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',然后针对strlen()返回的单行测试文件的fgets()。所以它确实只是确保它是一行代码。

答案 1 :(得分:1)

这是一个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;
}