2012-12-11 33 views
0

HTML模板在php中解析这样的模板的有效方法是什么?

<b><!--{NAME}--></b> 
... 
.. 
.. 
<b><!--{ADDRESS}--></b> 

PHP阵列

array('name'=>'my full name', ..... , 'address'=>'some address '); 

我有很多的模板文件和必须解析它们各自和替换它在关联数组的str_replace函数给出的数据。

我需要你的建议,以改善这个过程或任何其他技术/工具,它可能会有所帮助

编辑:当前版本的代码

静态函数ParseTemplate($数据,$模板){

$html=$read==true ? self::GetCached($template,true) : $template ; 

    foreach($data as $key=>$value){ 
     if(is_array($value)){ 
      foreach($data[$key] as $aval) 
      $html = str_replace("<!--{".$key."}-->",$aval,$html); 
     } 
     else $html = str_replace("<!--{".$key."}-->",$value,$html); 
    } 

    return $html; 

}

感谢

+2

: //github.com/bobthecow/mustache.php#readme –

+0

@tuxtimo,plz检查编辑 – sakhunzai

+0

@JonathandeM。感谢您的建议:)他们看起来很有希望 – sakhunzai

回答

1

为什么不使用模板引擎,如http://mustache.github.com/#demo,这里的PHP HTTPS为什么不使用模板引擎,如Mustache,在这里为PHP version

1

如果数组键总是一样的括号内的模板的话,做这样的事情:

foreach ($array as $key => $value) { 
    $html = str_replace("<!--{$key}-->", $value, $html) 
} 

如果性能是很重要的,它可能是更好的在HTML中使用strpos,并去了一个接一个的占位符。在大字符串上多次执行str_replace会更快。但如果表现不是问题,那就没有必要。

编辑:

$index = strpos($html, "<!--"); 
while ($index !== false) { 
    // get the position of the end of the placeholder 
    $closing_index = strpos($html, "}-->", $index); 

    // extract the placeholder, which is the key in the array 
    $key = substr ($html, $index + 5, $closing_index); 

    // slice the html. the substr up to the placeholder + the value in the array 
    // + the substr after 
    $html = substr ($html, 0, $index) . $array[$key] . 
      substr ($html, $closing_index + 4); 

    $index = strpos($html, "<!--", $index + 1); 
} 

注意:这不是测试,所以可能会有一些不准确与指标......它只是给你一个总体思路。

我认为这比str_replace更有效率,但你知道吗?这可以使用一些基准...

+0

任何关于strpos()的东西的事情? – sakhunzai

+0

@sakhunzai添加strpos示例 –

+0

感谢您的努力,但似乎胡须似乎更好的选择,因为它有一些缓存支持 – sakhunzai

0

如果我理解正确的问题,我认为下面应该工作正常,除非我失去了一些东西。

$a = array('name'=>'my full name','address'=>'some address'); 
foreach($a as $k=>$v) 
{ 
    $html = str_replace('<!--{'.strtoupper($k).'}-->',$v,$html); 
} 
+0

是的,我需要一些'高效'的方式来做到这一点 – sakhunzai

相关问题