2016-12-23 24 views
1

標題可能不夠清晰,所以我會嘗試解釋我的意思:我試圖在php上創建自己的「模板」,並且每個頁面都包含少量字符串(例如: {%title%}, {%description%}等),它應該像變量一樣,並由數據庫中的另一個字符串替代。爲了使它更簡單(&靜態,但僅用於測試目的),我試圖用arraystr_replace函數做一些測試,但它不起作用。PHP - 「模板」

我的代碼(這是不工作的,當然)是:

<?php 
    str_replace(array('{%title%}', '{%description%}'), array('Example', 'Example description'), /* what the ... should I insert here? */); 
?> 

和HTML(部分):在

<title>{%title%}</title> 
<meta name="description" content="{%description%}" /> 

我應該使用JavaScript(或可能AJAX)這個案例?有沒有其他的方式來做這樣的事情?

更新:ob_start是解決方案。 :-)

非常感謝,如果我有任何拼寫錯誤,請原諒我的英語。

+0

您是否閱讀過'str_replace'的文檔頁面? – Federkun

+0

@Federkun是的,但我需要把我的整個頁面作爲這個函數的'$ subject' – natanelg97

回答

0

怎麼是這樣的:

<?php 
$subject = file_get_contents("mytemplate.html"); 
$keys = array(
    "{%mykey1%}", 
    "{%mykey2%}" 
); 
$values = array(
    "myval1", 
    "myval2" 
); 

$page = str_replace($keys, $values, $subject); 
ob_clean(); 
echo $page; 
0

如果我得到你的意思,這可能是一個解決方案。

<?php 


$string = "{%title%}, {%description%}"; 

$tags = array('title', 'description'); 
$content = array('Example title', 'Example description'); 

for($i = 0; $i < count($tags); $i++){ 
    $tag = '{%'.$tags[$i].'%}'; 
    $string = str_replace($tag, $content[$i], $string); 
} 

echo $string; // This outputs Example title, Example description 

?> 

你當然應該把$ string換成頁面的內容,但我想你可以自己弄清楚。

0

ob_start()基本示例

//starting the output cache 
    ob_start(); 
    //register a shutdown function, 
    //so you dont have to do ob_ stuff at the end of the script 
    register_shutdown_function(
    function() use(&$from,&$to){ 
     //$from,$to must be prepared 
     //(given as reference so you can fill them after register the function) 
     echo str_replace($from,$to,ob_get_clean()); 
    }); 

但它只是一個點開始,當你想使用ob_start()。 模板通常以其他方式完成。 閱讀關於Smarty並從中學習,如果你想自己做。