在PHP中获取包含在字符串中的结果? [英] Get the Results of an Include in a String in PHP?

查看:89
本文介绍了在PHP中获取包含在字符串中的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说文件test.php看起来像这样:

Let's say file test.php looks like this:

<?php
echo 'Hello world.';
?>

我想做这样的事情:

$test = include('test.php');

echo $test;

// Hello world.

有人能指出我走正确的道路吗?

Can anyone point me down the right path?

编辑:

我最初的目标是将PHP代码与HTML混合在一起并将其处理出来。以下是我最终要做的事情:

My original goal was to pull PHP code intermingled with HTML out of a database and process it. Here's what I ended up doing:

// Go through all of the code, execute it, and incorporate the results into the content
while(preg_match('/<\?php(.*?)\?>/ims', $content->content, $phpCodeMatches) != 0) {
    // Start an output buffer and capture the results of the PHP code
    ob_start();
    eval($phpCodeMatches[1]);
    $output = ob_get_clean();

    // Incorporate the results into the content
    $content->content = str_replace($phpCodeMatches[0], $output, $content->content);
}


推荐答案

使用输出缓冲是最好的选择。


ob_start();
include 'test.php';
$output = ob_get_clean();

PS:请记住,如果需要,您也可以将输出缓冲区嵌套到心中。 。

PS: Remember that you can nest output buffers to your hearts content as well if needed.

这篇关于在PHP中获取包含在字符串中的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆