如果可以存储带有特殊字符串的html模式页面来替换变量以及如何操作,我就会徘徊。
在外部文件中,我想放一个产品的html结构,让我们称之为schema.php
:
<span id="{% id %}">{%= name %}</span>
<span>{%= imageURL() %}</span>
上面的例子只是一个更简单的例子。在外部文件中,html会更复杂。我知道如果只有几行,我可以用一个简单的函数回显它们,但事实并非如此。
在另一个文件中,我有一个处理产品的类,我们称之为class.php
:
class Product {
//logic that is useless to post here.
public function imageURL() {
return "/some/url".$this->id."jpg";
}
}
在这个课程中,我想添加一个从schema.php
获取内容的函数,然后在公共文件中为用户回显它。
我尝试使用file_get_contents()
和file_put_contents()
,但它不起作用:
$path_to_file = 'data/prodotti/scheda.inc';
$file_contents = file_get_contents($path_to_file);
$file_contents = str_replace(
"{%= ",
"<?php echo $this->",
$file_contents
);
$file_contents = str_replace(
" }",
"; ?>",
$file_contents
);
file_put_contents($path_to_file, $file_contents);
是否可以调用schema.php
页面并使用自定义变量进行打印?
答案 0 :(得分:0)
通过“架构页面”我认为你的意思是“模板”,是的,但最好的方法是使用现有的模板引擎,如Smarty或像https://github.com/bobthecow/mustache.php这样的Mustache实现因为XSS,HTML注入的风险,以及你最终想要循环和条件等功能的方式,你自己实现它。
答案 1 :(得分:0)
你可以用php require func做正常的事。没有任何要替换的字符串,如果您只想将该文件用作“模板”,那么:
schema.php中的:
<?php
echo'<span id="'.$id.'">'.$name.'</span>
<span>'.$imageURL.'</span>';
?>
class.php中的:
<?php
class Product {
//logic that is useless to post here.
public function imageURL() {
return "/some/url".$this->id."jpg";
}
}
$imageURL = imageURL(); ?>
Index.php或处理class.php和temp.php(架构)的主页面
<?php
//avoid undefined variables on errors
//in case that you don't check for values submitted
$id = 0;
$name = 0;
$imageURL = '';
//set vars values
$id = /*something*/;
$name = /*something 2*/;
$imageURL = /*something3*/;
//all date will be replaced is ready, oky nothing to wait for
require('path/to/schema.php');
注意:如果您从用户那里获得这些数据,那么您应该使用if(isset())
进行验证。
希望有所帮助,