Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to PHP call another page and get output as variable?

Tags:

php

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>';
echo $output;

?>

page2.php
<?php

echo "Is this real life?<br>";

?>

Would output:

Hello World!
Go for it!
Is this real life?
like image 212
Yoshiyahu Avatar asked Sep 19 '11 19:09

Yoshiyahu


People also ask

How do I call a PHP page from another PHP page?

Answer: Use the PHP header() Function You can simply use the PHP header() function to redirect a user to a different page. The PHP code in the following example will redirect the user from the page in which it is placed to the URL http://www.example.com/another-page.php . You can also specify relative URLs.

What is $_ GET [' page ']?

PHP $_GET is a PHP super global variable which is used to collect form data after submitting an HTML form with method="get". $_GET can also collect data sent in the URL. Assume we have an HTML page that contains a hyperlink with parameters: <html> <body>

Can I echo a variable in PHP?

Echo In PHPIn order to output one or more strings, we can use echo statement. Anything that can be displayed to the browser using echo statement, such as string, numbers, variables values, the results of expressions, etc. It is required to use parenthesis if you want to use more than one parameter.


2 Answers

To clear up some confusion when using file_get_contents(), note that:

  1. Using with the full url will yeild the html output of the page:

    $contents = file_get_contents('http://www.example-domain.com/example.php');
    
  2. While using it with file path will get you the source code of the page:

    $contents = file_get_contents('./example.php');
    
like image 175
KoE Avatar answered Nov 15 '22 16:11

KoE


require is actually exactly what you want (in combination with output buffering):

ob_start();
require 'page2.php';
$output = ob_get_clean();
like image 42
mfonda Avatar answered Nov 15 '22 16:11

mfonda