donglei2022 2014-02-12 17:17
浏览 41
已采纳

如何在<head>标记内使用PHP添加css文件?

Ok, let me explain:

I have a some files, something basic like this:

index.php

<html>
      <head>

            <title>Simple page</title>

      </head>

      <body>

            <?php include 'home.php'; ?>

      </body>
</html>

home.php

<div class="thisWillBeBlue">Still not blue</div>

style.css

.thisWillBeBlue {background: blue}

Now the question: Using php I want to insert the style.css inside the head tag, calling it from the file home.php. Well, I came out with a solution, but it was not very effective:

index.php

<?php $css = array(); 
      $css[] = 'linktothecss.css'

?>

<html>
      <head>

            <title>Simple page</title>

            <?php

                foreach($css as $item){

                    echo "<link rel='stylesheet' href='".$item."' />";

                }

            ?>

      </head>

      <body>

            <?php include 'home.php'; ?>

      </body>
</html>

But the problem it is, If I call the css from home.php it will be added to the array later, therefore it will not be echoed inside the head tag. Any ideas?

  • 写回答

3条回答 默认 最新

  • duanhao4156 2014-02-12 17:36
    关注

    You could do it using ob_start() and ob_end_flush() functions e.g.

    index.php

    <?php
    
    $csspage = "default.css";
    function loadCSS($buffer) {
      global $csspage;  
      return (str_replace('{{ css }}', $csspage, $buffer));
    }
    
    ob_start("loadCSS"); ?>
    
    <html>
       <head>
          <!-- the string {{ css }} is just a placeholder that will be replaced 
               with the new value of $csspage defined later in the code, otherwise
               it will replaced with its initial value (default.css)
          -->
          <link href="{{ css }}" /> 
       </head>
    
    <body>
         <?php include 'home.php'; ?>
    </body>
    
    </html>
    
    <?php ob_end_flush(); ?>
    

    home.php

     <?php $csspage = "custom_style.css";  ?> 
     <div class="thisWillBeBlue">blue</div>
    

    Further reference: http://it1.php.net/ob_start

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?