我可以使用file_get_contents加载css吗?

时间:2014-01-28 21:59:15

标签: php html css

而不是:

<head>
    <link rel="stylesheet" type="text/css" href="css_file.css" />
</head>

我想这样做:

<head>
    <style><?php file_get_contents("css_file.css");?></style>
</head>

出于某种原因,文本显示在文档中,但样式未应用。这是一个两部分问题:

  1. 为什么这不起作用?
  2. 这样做是不是一个坏主意?

4 个答案:

答案 0 :(得分:3)

这就是你喜欢todo,输出将是你的css文件,使用类似preg_replace的东西,如果你需要更多可读内容,你可能想要添加新行,例如,之前和在{ }之后,我在没有preg_replace的情况下进行了测试,并且示例在使用简单的css文件时运行良好,我没有使用复杂的css文件进行测试,但它应该也能正常工作,我恳请尝试一下它与您的CSS文件。我希望它能帮助你走向正确的方向......

<?php
$css_File = file_get_contents("css_file.css"); // Can use single quot as well...
echo '<style type="text/css">' . $css_File . '</style>'; // All php echo example
?>

或者更好的例子,我认为这可能是你想要的:

<?php $css_File = file_get_contents('http://www.example.com/css_file.css'); ?>
<style type="text/css"><?php echo $css_File; ?></style><!--// your request example //-->

答案 1 :(得分:3)

This question was posted when I was a beginning developer. I didn't know about Sass and other easier and better ways to achieve variables in CSS. I also didn't know about browser caching.

Jeremy Karlsson answered the question in a comment. file_get_contents requires echo.

答案 2 :(得分:2)

为什么不使用

include("css_file.css");

@edit 此外,如果你包括css文件,请确保在它周围回显样式标签

答案 3 :(得分:0)

您可以像这样在当前主题内获取CSS文件的内容:

<?= file_get_contents(get_template_directory_uri() . '/css/main.min.css'); ?>