包含@import的CSS文件的PHP file_get_contents

时间:2017-01-08 03:51:39

标签: php

我正在尝试将css文件的内容加载到PHP字符串。除非css文件使用@import

,否则它的效果很好

的style.css

@import url('normalize.css');
@import url('main.css');
@import url('colors.css');

$contents = @file_get_contents('style.css');

echo $contents; // Obviously doesn't include the css in the imported files

这显然是返回style.css的确切内容。如何让它导入这些文件?

1 个答案:

答案 0 :(得分:0)

这是一个棘手但简单的方法: 首先在所有导入后添加@import注释

css_part

@import url('normalize.css');
@import url('main.css');
@import url('colors.css');
/*@import*/
.class{}
.class{}

php_part

$contents = @file_get_contents('style.css');
$wordToLookFor = "@import";
$contentToAdd = "";
$imports = explode($wordToLookFor,$contents);
for( $i=0; $i < sizeof($imports) - 1 ; $i++){
    $tmp = str_replace(array("url(",");","/*"),"",$imports[$i]);
    $contentToAdd .= @file_get_contents($tmp);
}
$contents = $contentsToAdd . $contents;
echo $contents; // should include other files in the same order now