Writing _rendered_ PHP to HTML file – Education Career Blog

Having probs here.

I need to write the output of a PHP script to an HTML page to then be processed by DOMPDF so I can make a nice little PDF for some friends to use.

When I use file_get_contents to get the contents of a “donor” PHP script, it does that – literally. It grabs the unevaluated PHP and holds it for me to do as I wish.

I need the PHP script to RUN, then take the output and file_put_contents it somewhere.

Thanks,
Rob

,

Well, ideally you can configure the PHP script so that instead of writing its contents it builds a giant string and returns it. That way you can simply call a function and get back a string with the information you need.

If the target script is out of your control, you might work around it with something like:

ob_start();
include('script.php');
$contents = ob_get_contents();
ob_end_clean();

,

Call it through http to make it run.

file_get_contents("http://localhost/my/script/file.php");

alternatively, run it from the command line:

php -f /path/to/my/script/file.php

,

Two quick solutions. The first is to setup the PHP script to run from a url, and then user file_get_contents or the curl functions to download the page. This will give you a string with the correct content.

$string = file_get_contents('http://example.com/myscript.php');

The second is to use include and output buffering. Output buffering takes any echo or print statments, and stores their content in memory rather then outputting to the browser/screen.

ob_start(); //start output buffering
include("myscript.php"); //script will run in the current context, but output will be stored in memory
$string = ob_get_clean(); //stored output will be fetched into $string, and buffering ended

,

You can do it in a few different ways:

1) Fetch the script through it’s URL (through the web browser) instead of the file path.

2) Use eval

3) Use output buffering and include the script into the current one. Example:

ob_start();
include('script.php');
$result = ob_get_clean();

4) Run it from the commandline using shell_exec('php -f script.php');

Leave a Comment