2010-06-14 43 views
1

首先,我使用的是ob_start()和ob_flush。編譯器通過後插入值行

在代碼中,我有一個參數被假定爲在文件頭部被動態加載的部分。

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

//Enter More Code Here Later 

</head> 

什麼我想是編譯器完成後,達到了文件的末尾,並發現更多的圖書館補充,是有辦法,我可以添加多個庫的一部分,它說/ /在此輸入更多代碼?我知道這是可能使用Javascript/AJAX,但我試圖用PHP來做到這一點。

回答

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

這個解決方案很容易的工作。謝謝 – user293313 2010-06-16 00:40:33

0

一個選項,將增加一個 「標記」。所以用<!-- 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>');