从另一个PHP文件中读取echo'ed输出

时间:2021-11-26 14:06:49

I want 1 PHP file to "run" (include?) another PHP file on the same server, and access its echo'ed output as a string.

我想要1个PHP文件在同一台服务器上“运行”(包含?)另一个PHP文件,并以字符串形式访问其echo'ed输出。

How do i do this in PHP? Any inbuilt functions to do this?

我如何在PHP中执行此操作?任何内置函数来做到这一点?

Or any better way of executing another PHP file and getting its output?

或者更好的方法来执行另一个PHP文件并获得其输出?

2 个解决方案

#1


32  

You can use PHP's output buffering to accomplish this:

您可以使用PHP的输出缓冲来完成此任务:

ob_start(); // begin collecting output

include 'myfile.php';

$result = ob_get_clean(); // retrieve output from myfile.php, stop buffering

$result will then contain the text.

$ result将包含文本。

#2


2  

You can't include a PHP script that is on an external website/server into your local script - unless you enable allow_url_include on your php.ini (if you have access to it)

您不能将外部网站/服务器上的PHP脚本包含在本地脚本中 - 除非您在php.ini上启用allow_url_include(如果您有权访问它)

Instead, you can let that website/server render the page and get the resulting HTML output on your local script by doing this:

相反,您可以通过执行以下操作让该网站/服务器呈现页面并在本地脚本上获取生成的HTML输出:

$result = file_get_contents('http://127.0.0.1/myfile.php');

#1


32  

You can use PHP's output buffering to accomplish this:

您可以使用PHP的输出缓冲来完成此任务:

ob_start(); // begin collecting output

include 'myfile.php';

$result = ob_get_clean(); // retrieve output from myfile.php, stop buffering

$result will then contain the text.

$ result将包含文本。

#2


2  

You can't include a PHP script that is on an external website/server into your local script - unless you enable allow_url_include on your php.ini (if you have access to it)

您不能将外部网站/服务器上的PHP脚本包含在本地脚本中 - 除非您在php.ini上启用allow_url_include(如果您有权访问它)

Instead, you can let that website/server render the page and get the resulting HTML output on your local script by doing this:

相反,您可以通过执行以下操作让该网站/服务器呈现页面并在本地脚本上获取生成的HTML输出:

$result = file_get_contents('http://127.0.0.1/myfile.php');