Skip to content
Advertisement

PHP: file_get_contents a PHP file with include();

I have a PHP Script that calls a master PHP template (acts as HTML template) with file_get_contents, replaces a few words from it and then saves the final file as another PHP in a directory.

But the master PHP template itself has include(); and require_once(); in it and the saved file after replacing the words doesn’t load the files called from the master template.

The HTML source code of the saved file is with <?php include('file_here'); ?> in it, but not with the output of file_here — see image.

enter image description here

How can I call file_get_contents(); and still let the master template execute include(); or require_once(); ?

Advertisement

Answer

file_get_contents() will get the content of a file, not execute it as a PHP script. If you want this piece of code to be executed, you need to either include it, or process it (through an HTTP request to Apache, for instance).

If you include this file, it’ll be processed as PHP code, and of course, print your HTML tags (include* can take any kind of file).

If you need to work with its content before you print it, use ob_* functions to manipulate the PHP output buffer. See : https://www.php.net/manual/en/ref.outcontrol.php

ob_start(); // Start output buffer capture.
include("yourtemplate.php"); // Include your template.
$output = ob_get_contents(); // This contains the output of yourtemplate.php
// Manipulate $output...
ob_end_clean(); // Clear the buffer.
echo $output; // Print everything.

By the way, such mechanism sounds heavy for a template engine. Basically, templates should not contain PHP code. If you want such behavior, have a look at Twig : http://twig.sensiolabs.org/

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement