Metropolis
Metropolis

Reputation: 6622

Get the contents of a PHP file into a variable for displaying

How can I get the contents of a PHP file (which also contains HTML) into a variable, and then echo them at a later time inside another PHP file? I also need the contents to execute the PHP in it properly. I tried something like the following, but its just giving me a string of all the contents on the page.

$contents = file_get_contents("myfile");
echo $contents;

Upvotes: 2

Views: 83

Answers (2)

Carl Zulauf
Carl Zulauf

Reputation: 39568

One PHP script executing another and capturing its output usually means you are going about things the wrong way. If you must, have a look at output buffering, eval, and maybe even stuff like system_exec.

If you want to solve your problem better you may want to look at a project like CodeIgniter and how its templating system works, especially how small template partials/fragments are rendered and incorporated into larger views/templates.

Upvotes: 0

nickb
nickb

Reputation: 59709

Use output buffering and include the file.

ob_start();
include( 'myfile');
$contents = ob_get_contents();
ob_end_clean();

Then, at a later time:

echo $contents;

Upvotes: 3

Related Questions