16

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?

1
  • you mean file_get_contents() right? Commented Nov 5, 2009 at 22:02

2 Answers 2

44

This should do it:

ob_start();
include('template.php');
$returned = ob_get_contents();
ob_end_clean();
Sign up to request clarification or add additional context in comments.

4 Comments

Watch out though as since the file is being included & not executed on it's own you might get funny behaviour.
Including the file scans it and if there is PHP inside, it's executed like if called stand-alone. If that's not what you mean, then could you be more specific?
I think what he is trying to say is to be careful, if the php file you are executing has any side-effects it could mutate the state of your application even though it is not sending output to the browser.
if the included file has die() or exit; inside it, it will stop further execution
3

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

1 Comment

While this isn't the right answer, it is definitely helpful to know in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.