编译器通过后插入值行

问题描述:

首先,我使用的是ob_start()和ob_flush。编译器通过后插入值行

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

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

//Enter More Code Here Later 

</head> 

什么我想是编译器完成后,达到了文件的末尾,并发现更多的图书馆补充,是有办法,我可以添加多个库的一部分,它说/ /在此输入更多代码?我知道这是可能使用Javascript/AJAX,但我试图用PHP来做到这一点。

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> 
+0

这个解决方案很容易的工作。谢谢 – user293313 2010-06-16 00:40:33

一个选项,将增加一个 “标记”。所以用<!-- HEADCODE-->代替//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->addTo('HEAD', '<myscript>');