Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a PHP file, and return the result as a string

Tags:

string

php

Let's assume I have the following file - template.php:

<?php $string = 'Hello World!'; ?>
<html>
    <head>
        <title>Test Page!</title>
    </head>
    <body>
        <h1><?= $string; ?></h1>
        <p>You should see something above this line</p>
    </body>
</html>

I'm aware that I can use file_get_contents() to get the contents of the file as a string, which I can then manipulate as I require. However, file_get_contents() doesn't execute PHP statements.

I have successfully used cURL to get access to the rendered version of the file, but it seems rather slow and clunky, adding quite a fair amount of time to the execution of the page - which I would imagine is due to a DNS lookup being performed.

So, how can I get the contents of template.php into a string - while having usable PHP there?

like image 683
EvilChookie Avatar asked Nov 05 '09 21:11

EvilChookie


People also ask

What is Execute function in PHP?

The shell_exec() function is an inbuilt function in PHP which is used to execute the commands via shell and return the complete output as a string.


2 Answers

This should do it:

ob_start();
include('template.php');
$returned = ob_get_contents();
ob_end_clean();
like image 147
bisko Avatar answered Oct 19 '22 23:10

bisko


If you don't need to do this within PHP, you could execute a php script from the command line, and pipe it to a text file, like so:

php -f phpFile.php > output.html
like image 22
Ryan Brunner Avatar answered Oct 20 '22 01:10

Ryan Brunner