一种选择是添加“标记”。所以替换//Enter More Code Here Later
为<!-- HEADCODE-->
.
然后,稍后,当您准备好发送给客户端时(您提到使用 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>');