我想在将其包含在index.php
中之前替换PHP文件中的多个文本例如。 我将要包含在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 但它不适用于这种情况。
答案 0 :(得分:2)
为什么重新发明轮子?
选择existing template engine,或者只使用vanilla 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>
如果你真的想创建自己的半烘焙模板系统,那么你需要使用输出缓冲来捕获字符串中include的内容,然后执行替换:
<?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;
?>
答案 1 :(得分:0)
在您想要的内容中创建一个名为{%name%}存储的sting,然后在尝试显示时用{%name%}替换为实际值。
答案 2 :(得分: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;
?>