我想从PHP页面调用PHP页面,并返回我称为单个变量的页面的输出.
require 不适合我的目的,因为我需要将输出存储为变量供以后使用,而不是立即输出.
IE:
page1.php
<?php
echo 'Hello World!<br>';
$output = call_page('page2.php');
echo 'Go for it!<br>';
echo $output;
?>
page2.php
<?php
echo "Is this real life?<br>";
?>
Run Code Online (Sandbox Code Playgroud)
输出:
Hello World!
Go for it!
Is this real life?
Run Code Online (Sandbox Code Playgroud)
小智 22
为了在使用时消除一些困惑file_get_contents(),请注意:
使用完整的URL会显示页面的html输出:
$contents = file_get_contents('http://www.example-domain.com/example.php');
Run Code Online (Sandbox Code Playgroud)将它与文件路径一起使用时,可以获得页面的源代码:
$contents = file_get_contents('./example.php');
Run Code Online (Sandbox Code Playgroud)require 实际上正是你想要的(与输出缓冲相结合):
ob_start();
require 'page2.php';
$output = ob_get_clean();
Run Code Online (Sandbox Code Playgroud)
你可以使用的file_get_contents方法,这将返回包含您请求的页面内容的字符串- http://php.net/manual/en/function.file-get-contents.php
$contents = file_get_contents('http://www.stackoverflow.com/');
echo $contents;
Run Code Online (Sandbox Code Playgroud)
ob_start();
include('otherpage.php');
$output = ob_get_clean();
Run Code Online (Sandbox Code Playgroud)
一种更好的方法是将其他页面中正在进行的任何操作封装为函数,然后可以从两个页面调用.这使您可以重用代码,而不必混淆输出缓冲和诸如此类的东西.