2011-06-07 23 views
2

我有一個問題要問你。PHP能否將html命令寫入另一個文件?

我有兩個PHP文件第一個是index.php文件,另一種是body.php

index.php文件包含HTML模板就像從數據庫

<html> 
    <head> 
     <title></title> 
    </head> 
    <body> 
     <? include('body.php') ?> 
    </body> 
</html> 

和body.php查詢數據(例如作爲姓名,暱稱,年齡)。

我需要body.php改變標籤或的index.php

添加更多標籤我應該如何在PHP命令嗎?

感謝

+0

你有2個選項,1。不要輸出任何東西,並將其保存在輸出緩衝區中,然後在緩衝區上使用str_replace替換/添加'tags'或構建appon基本索引內容而不必先輸出,使用php更容易和更友好地構建appon內容和輸出保持呼應。 – 2011-06-07 06:34:52

回答

4

在你的榜樣,body.php可以有你需要的任何HTML輸出。 body.php的輸出將包含在您的最終輸出中。

如果您需要的index.php依賴的最終輸出的body.php文件(例如插入標題),您可以加載內容到變量,以後可以輸出。

<? 
    include ('body.php'); 
    /* $title and $bodyHTML are set in the include file */ 
?> 


<html> 
    <head> 
     <title><? echo $title; ?></title> 
    </head> 
    <body> 
     <? echo $bodyHTML;?> 
    </body> 
</html> 
2

您可以使用fopen()fwrite()修改的index.php從body.php內容(假設你有寫的權限,當然)。

如果您的意思是在用戶查看index.php並更改index.php時更改內容,那麼在沒有告訴用戶「單擊此處並查看新代碼!」的情況下這是不可能的! (因爲在那個時候,你不能再使用頭來刷新頁面)。

PHP不是一種動態內容語言,例如JavaScript。

0

在body.php文件中寫入db相關的東西,並從index.php中調用這些函數。 循環這些結果並通過相關標籤和顯示進行構建。

完蛋了.........

0

你可以輸出一個PHP對象整個事情稱爲domdocument,它允許動態創建的HTML文檔。這樣,您可以根據需要動態更改標籤及其內容。

1

您不能在已經輸出的部分頁面中更改變量。您可以使用output buffering捕獲輸出到那個點,然後做它的字符串替換

<?php ob_start(); // start buffering output 
?> 
<html> 
    <head> 
     <title></title> 
    </head> 
    <body> 
     <?php 
        include('body.php'); 
        // Get the contents of the buffer and then clear the buffer 
        $buffer = ob_get_clean(); 
        // Replace your keyword with a variable loaded from body.php 
        $buffer = str_replace('%nickname%', $nickname, $buffer); 
        // output the altered head 
        echo $buffer; 
        // Stop buffering and output what we just echoed 
        ob_end_flush(); 
       ?> 
    </body> 
</html> 

有一些PHP模板和主題化引擎在那裏的,使 做這種事情更容易。 Smarty是一個相當受歡迎的 。我喜歡的另一個是Savant,但我個人偏向於我創建的稱爲Enrober的那個。

相關問題