How to PHP call another page and get output as variable?
I would like to call a PHP page from a PHP page, and return the output of the page I called as a single variable.
require
would not suit my purposes as I need the output stored as a variable for later use, rather than outputting it immediately.
IE:
page1.php
<?php
echo 'Hello World!<br>';
$output = call_page('page2.php');
echo 'Go for it!<br&开发者_如何转开发gt;';
echo $output;
?>
page2.php
<?php
echo "Is this real life?<br>";
?>
Would output:
Hello World!
Go for it!
Is this real life?
To clear up some confusion when using file_get_contents()
, note that:
Using with the full url will yeild the html output of the page:
$contents = file_get_contents('http://www.example-domain.com/example.php');
While using it with file path will get you the source code of the page:
$contents = file_get_contents('./example.php');
require
is actually exactly what you want (in combination with output buffering):
ob_start();
require 'page2.php';
$output = ob_get_clean();
You could use the file_get_contents method, this returns a string containing the contents of the page you request - http://php.net/manual/en/function.file-get-contents.php
$contents = file_get_contents('http://www.stackoverflow.com/');
echo $contents;
ob_start();
include('otherpage.php');
$output = ob_get_clean();
A better method would be to encapsulate whatever's being done in that other page as a function, which you can then call from both pages. This lets you reuse the code without having to mess around with output buffering and whatnot.
In my case, none of the solutions posted worked for me. Only the comment by Ondřej Mirtes worked. I wanted to execute a script, passing some parameters:
anotherscript.php?param=value
So, the solution was to use cURL:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http".( ($_SERVER["HTTPS"] == "on")?'s':'' )."://".$_SERVER['HTTP_HOST'].dirname($_SERVER['PHP_SELF'])."/anotherscript.php?param=value");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
I want to create pdf from existing .php files.
From answers above i have 3 options:
1.rewrite .php files
2.use buffering:
$_GET["id"]="4";
ob_start();
include 'test.php';
$TextPDF = ob_get_clean();
3.get data by url:
$serv = "http".( ($_SERVER["HTTPS"] == "on")?'s':'' )."://".$_SERVER["SERVER_NAME"];
$TextPDF = file_get_contents($serv.'/test.php?id=4');
I think i will use third option, then i don't have to modify existing files.
精彩评论