我试图在解析 PHP 文件后获取其内容,然后将其存储在变量中。
除了这个例子之外,我无法通过谷歌获得任何有用的信息:
ob_start();
include $file;
$content = ob_get_clean();
但这会以纯文本形式返回内容,即:<?php
and ?>
标签仍然存在,并且标签之间的所有代码都不会被解析。
所以我想知道,我怎样才能正确地做到这一点?
update:这是正在包含的文件的内容:
Testcontent
<?php echo 'This should be parsed, right?'; ?>
几年前,我在某种模板引擎中使用了这个函数,它似乎可以满足您的需要 - 传递一个包含一些 PHP 代码的字符串,它会在执行 PHP 时返回它。令人惊讶的是,它仍然有效:-)
function process_php( $str )
{
$php_start = 0;
$tag = '<?php';
$endtag = '?>';
while(is_long($php_start = strpos($str, $tag, $php_start)))
{
$start_pos = $php_start + strlen($tag);
$end_pos = strpos($str, $endtag, $start_pos); //the 3rd param is to start searching from the starting tag - not to mix the ending tag of the 1st block if we want for the 2nd
if (!$end_pos) { echo "template: php code has no ending tag!", exit; }
$php_end = $end_pos + strlen($endtag);
$php_code = substr($str, $start_pos, $end_pos - $start_pos);
if( strtolower(substr($php_code, 0, 3)) == 'php' )
$php_code = substr($php_code, 3);
// before php code
$part1 = substr($str, 0, $php_start);
// here set the php output
ob_start();
eval($php_code);
$output = ob_get_contents();
ob_end_clean();
// after php code
$part2 = substr($str, $php_end, strlen($str));
$str = $part1 . $output . $part2;
}
return $str;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)