php 编译 xml 模板
代码
template_compile.php
<?php
// 自定义模板编译方法 compile, template_compile
/**
* 编译模板
* @param $template 模板
* @param $data 模板数据
* @return
*/
function template_compile($template, $data)
{
eval(compile($template));
return parse($data);
}
function compile($template)
{
$evalExpr = '/<#=(.+?)>/';
$expr = '/<#([\s\S]+?)>/';
$template = preg_replace($evalExpr, "\"); \n p( $1 ); \n p(\"", $template);
$template = preg_replace($expr, "\"); \n $1 \n p(\"", $template);
$template = 'p("' . $template . '");';
$phpScript = <<<EOF
function parse(\$data){
global \$output;
\$output = "";
function p(\$html){
global \$output;
\$output = \$output . htmlspecialchars(\$html);
}
$template
return htmlspecialchars_decode(\$output);
};
EOF;
return $phpScript;
}
使用方法:
模板
demo.xml
<hello.article>
<# for($i=0; $i < count($data); $i++) { >
<persion>
<name><#=$i></name>
<age><#=$data[$i]></age>
</persion>
<# } >
</hello.article>
调用
ob_start();
require __DIR__ . '/demo.xml';
$template = ob_get_contents();
ob_end_clean();
$xml = template_compile($template, array('Yue', 'Jay'));
echo $xml;
打印结果:
<hello.article>
<persion>
<name>0</name>
<age>Yue</age>
</persion>
<persion>
<name>1</name>
<age>Jay</age>
</persion>
</hello.article>
Tip: 需要在使用的 php 脚本文件头部,引入template_compile.php
require __DIR__ . '/compile/template_compile.php';
至此,结束。