我试图在解析后获取PHP文件的内容,然后将其存储在变量中.除了这个例子,我无法通过Google获得任何有用的信息:
ob_start();
include $file;
$content = ob_get_clean();
Run Code Online (Sandbox Code Playgroud)
但是这会将内容作为纯文本返回,即:<?php
和?>
标签仍然存在,标签之间的所有代码都不会被解析.
所以我想知道,我该怎么做呢?
更新: 这是包含的文件的内容:
Testcontent
<?php echo 'This should be parsed, right?'; ?>
Run Code Online (Sandbox Code Playgroud)
小智 5
我几年前使用这个函数作为一种模板引擎,它似乎做你需要的 - 传递一个包含一些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;
}
Run Code Online (Sandbox Code Playgroud)