2016-03-08 57 views
1

我想在PHP文件中包含幾個文本,然後將其包含在我的index.php中在PHP中替換幾個文本include函數

例如, 我很擔心我的index.php包含的文件是一個名爲「main.php」的模板文件,它包含的代碼類似下面:

<html> 
<head> 
<script src="js/jquery.min.js"></script> 
<script src="js/jquery-migrate.min.js"></script> 
</head> 
<body> 
Hi, [your_name]. Welcome to [company_name]. Enjoy your stay here! 
</body> 
</html> 

,並在我的index.php我將有一個一堆查詢從數據庫中獲取數據並將其放入main.php文件中。下面的例子:

<?php 
$sql_stmt = "select name, company FROM comp_info WHERE deleted='0' AND status='2'"; 
$sql = mysqli_query($conn, $sql_stmt) or die(mysqli_error($conn)); 
$row = mysqli_fetch_assoc($sql); 

include_once("main.php"); 
?> 

我想下面使用這種方法,但我不知道如何在這種情況下使用它:

str_replace("[your_name]", $row['name'], main.php); 
str_replace("[company_name]", $row['company'], main.php); 

到目前爲止,我已經從互聯網上搜索到這是:Replacing {{string}} within php file 但它不適用於這種情況。

回答

2

爲什麼要重新發明輪子?

要麼選擇一個existing template engine,或者只是使用PHP的香草:

<?php 
$sql_stmt = "select name, company FROM comp_info WHERE deleted='0' AND status='2'"; 
$sql = mysqli_query($conn, $sql_stmt) or die(mysqli_error($conn)); 
$row = mysqli_fetch_assoc($sql); 

$name = $row['name']; 
$company = $row['company']; 

include_once("main.php"); 
?> 

模板(main.php):

<html> 
<head> 
<script src="js/jquery.min.js"></script> 
<script src="js/jquery-migrate.min.js"></script> 
</head> 
<body> 
Hi, <?=$name?>. Welcome to <?=$company?>. Enjoy your stay here! 
</body> 
</html> 

如果你真的想創建自己的半烤模板系統,然後您需要使用輸出緩衝來捕獲包含在字符串中的內容,然後執行替換:

<?php 
$sql_stmt = "select name, company FROM comp_info WHERE deleted='0' AND status='2'"; 
$sql = mysqli_query($conn, $sql_stmt) or die(mysqli_error($conn)); 
$row = mysqli_fetch_assoc($sql); 


ob_start(); 
include_once("main.php"); 
$mainString = ob_get_clean(); 

str_replace("[your_name]", $row['name'], $mainString); 
str_replace("[company_name]", $row['company'], $mainString); 

echo $mainString; 
?> 
0

創建一個名爲{%name%}存儲的內容是你想要的,然後當你嘗試顯示時用實際值替換{%name%}。

0

試試這個

<?php 
$sql_stmt = "select name, company FROM comp_info WHERE deleted='0' AND status='2'"; 
$sql = mysqli_query($conn, $sql_stmt) or die(mysqli_error($conn)); 
$row = mysqli_fetch_assoc($sql); 


ob_start(); 
include_once("main.php"); 
$mainString = ob_get_clean(); 

strip_tags($row['name']); 
strip_tags($row['company']); 

echo $mainString; 
?>