【问题标题】:Insert Values after Compiler has passed Line在编译器通过后插入值行
【发布时间】:2012-12-25 07:14:04
【问题描述】:

首先,我将 PHP 与 ob_start() 和 ob_flush 一起使用。

在代码中,我有一个部分假设参数被动态加载到文件的头部。

<head>
<script type="text/javascript" src="javascript/ajax_objects.js"></script>

//Enter More Code Here Later

</head>

我正在尝试的是在编译器完成并到达文件末尾并找到要添加的更多库之后,有没有办法可以将更多库添加到它显示 //Enter More Code 的部分这里 ?我知道使用 Javascript/AJAX 是可能的,但我试图只用 php 来做到这一点。

【问题讨论】:

    标签: php ob-start


    【解决方案1】:

    http://php.net/manual/en/function.ob-start.php

    示例 #1 准确描述了您要执行的操作: 您可以在调用 ob_end_flush() 时创建一个回调函数。

    例如:

    <?php
    function replaceJS($buffer) {
      return str_replace("{JS_LIBS}", 'the value you want to insert', $buffer);
    }
    ob_start("replaceJS");
    ?>
    <head>
    <script>
    {JS_LIBS}
    </script>
    </head>
    <?php
    ob_end_flush();
    ?>
    

    这种情况下的输出是:

    <head>
    <script>
    the value you want to insert
    </script>
    </head>
    

    【讨论】:

      【解决方案2】:

      一个选项是添加一个“标记”。所以用&lt;!-- HEADCODE--&gt;替换//Enter More Code Here Later

      然后,稍后,当您准备好发送给客户端时(您提到使用 ob_flush()),只需执行以下操作:

      $headContent = ''; //This holds everything you want to add to the head
      $html = ob_get_clean();
      $html = str_replace('<!-- HEADCODE-->', $headContent, $html);
      echo $html;
      

      如果你想变得花哨,你可以创建一个类来为你管理它。然后,不用执行 ob_get_clean,只需向 ob_start 添加一个回调即可。

      class MyOutputBuffer {
          $positions = array (
              'HEAD' => '',
          );
      
          public function addTo($place, $value) {
              if (!isset($this->positions[$place])) $this->positions[$place] = '';
              $this->positions[$place] .= $value;
          }
      
          public function render($string) {
              foreach ($this->positions as $k => $v) {
                 $string = str_replace('<!-- '.$k.'CODE-->', $v, $string);
              }
              return $string;
          }
      }
      
      $buffer = new MyOutputBuffer();
      ob_start(array($buffer, 'render'));
      

      然后,在您的代码中,只需执行 $buffer-&gt;addTo('HEAD', '&lt;myscript&gt;');

      【讨论】:

        猜你喜欢
        • 2015-08-26
        • 2010-09-25
        • 2013-10-28
        • 2019-12-23
        • 2013-09-16
        • 2011-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多