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 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。