【问题标题】:How to use HTML as template in PHP?如何在 PHP 中使用 HTML 作为模板?
【发布时间】:2018-05-02 16:06:48
【问题描述】:

我想使用 html 作为模板并用 PHP 填充数据。如果我有这样的 html

<h1>${heading-1}</h1>
<p>${paragraph}</p>

我想用我的 PHP 数组中的匹配值替换模板标签。如果我有一个包含所有可能匹配项的数组

$possible_matches = array(
  'heading-1'=> 'You can\'t do anything',
  'paragraph' => 'Unless you show your code which you don\'t have so be ready for down votes'
);
// what now?

它会像

一样改变 html
<h1>You can't do anything</h1>
<p>Unless you show your code which you don't have so be ready for down votes</p>

我怎样才能做到这一点?我应该使用正则表达式吗?

【问题讨论】:

标签: php html parsing templates


【解决方案1】:

你可以像这样使用 foreach 循环和 str_replace

$html = '<h1>${heading-1}</h1>
<p>${paragraph}</p>';
$possible_matches = array(
  'heading-1'=> 'You can\'t do anything',
  'paragraph' => 'Unless you show your code which you don\'t have so be ready for down votes'
);
foreach($possible_matches as $key=> $value){
$html = str_replace('${'.$key.'}',$value,$html);
}
echo $html;

如果外部文件中包含 html 模板,您可以使用 file_get_contents 将 html 放入变量 $html

【讨论】:

    猜你喜欢
    • 2012-10-12
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2017-07-28
    • 1970-01-01
    相关资源
    最近更新 更多