1

I'm using file_get_contents() to merge a template and separate content and output them together as a page.

The problem I'm having is that if either of these files have a PHP statement,

<?php
    echo "example";
?>

The PHP isn't actually run, and the statement just seems to be part of the markup:

enter image description here

I thought at first that the PHP at the file I'm loading wouldn't be run first, but then I made a test page with the following:

<?php
    echo file_get_contents("http://stackoverflow.com");
?>

And uploaded it here to see that it works fine (processes the PHP first).

Should I be using a different function maybe?

Marty
  • 39,033
  • 19
  • 93
  • 162
  • your probably mean file function http://php.net/manual/en/function.file.php – blejzz Oct 30 '11 at 21:04
  • possible duplicate of [Problem when loading php file into variable (Load result of php code instead of the code as a string)](http://stackoverflow.com/questions/7220830/problem-when-loading-php-file-into-variable-load-result-of-php-code-instead-of) - this is merely the same question, you might find some more useful tips in it's various answers. – hakre Oct 31 '11 at 10:25

1 Answers1

4

You just need to include() the PHP file.

Be wary of the security concerns.

If you want to capture the file's output, use output buffering.

Leonid Shevtsov
  • 14,024
  • 9
  • 51
  • 82
  • Thanks for the suggestion, but I'm more leaning towards an answer that explains why this function won't process the PHP in the file I'm loading first when it's local. – Marty Oct 30 '11 at 21:13
  • 3
    @MartyWallace, it's not meant to process it. `file_get_contents` reads the script as a plain text file and doesn't do any additional processing. You could do an `eval(file_get_contents())`, but that's just a backwards way of saying `include()`. – Leonid Shevtsov Oct 30 '11 at 21:15
  • I see, but you can't append the result of `include()` to a string can you? There are a few things I do to the file I've loaded such as replacing some strings with `preg_match_all()`, etc. – Marty Oct 30 '11 at 21:29
  • 1
    @MartyWallace Use output buffering to capture the output from the included script, and then append the result to the string. –  Oct 30 '11 at 21:31