开发者

Insert Values after Compiler has passed Line

To start, I am using PHP with ob_start() and ob_flush.

In the code I have a part where parameters are suppose to be dynmacially loaded in the head of a file.

<head>
<script type="text/javascript" src="javascri开发者_C百科pt/ajax_objects.js"></script>

//Enter More Code Here Later

</head>

What I am trying to is after the compiler has finished and reach the end of the file, and found more libraries to add, is there a way where I can add more libraries to the part where it says //Enter More Code Here ? I know it is possible using Javascript/AJAX, but I am trying to do this with just php.


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

Example #1 describes exactly what you're trying to do: You could create a callback function called when you call ob_end_flush().

For instance:

<?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();
?>

The output in that case would be:

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


One option, would be to add a "marker". So replace //Enter More Code Here Later with <!-- HEADCODE-->.

Then, later on, when you're ready to send to the client (You mentioned using ob_flush()), simply do:

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

If you wanted to get fancy, you could create a class to manage this for you. Then, instead of doing ob_get_clean, just add a callback to 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'));

Then, in your code, just do $buffer->addTo('HEAD', '<myscript>');

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜