tags:

views:

34

answers:

3

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="javascript/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.

A: 

Like you say, without using JavaScript or the like, I cant see how this would be possible, unless you let your php file run and instead of echoing the output, store it in a variable and go back and insert whatever in the head later.

Chief17
+1  A: 

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>
Maurice Kherlakian
This solution worked pretty easily. Thanks
A: 

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>');

ircmaxell