Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing the HTML output from a local PHP file into a string using file_get_contents

There is a header.php file and it contains some php codes that return HTML. I know I can use require, include to echo the results, but what I want to do is to store its processed output string into a variable.

In a page, I used:

$headerHTML=file_get_contents('header.php');

Then I got the PHP code output rather than the processed HTML output. I know adding http:// would help. But I prefer to keep using relative path, how can I tell the function to treat the php file correctly?

Note: I would like to continue to use this statement file_get_contents rather than using ob_start() if possible.

like image 595
bobo Avatar asked May 04 '10 04:05

bobo


People also ask

What will the file_get_contents () return?

Return Values ¶ The function returns the read data or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false . Please read the section on Booleans for more information.

What is the use of file_get_contents () function?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.

What is the difference between file_get_contents () function and file () function?

file — Reads entire file contents into an array of lines. file_get_contents — Reads entire file contents into a string.

How do I save a text file in PHP?

PHP Write to File - fwrite() The fwrite() function is used to write to a file. The first parameter of fwrite() contains the name of the file to write to and the second parameter is the string to be written.


2 Answers

I'd rather use require() wrapped inside ob_start() and ob_get_clean(). I am sure there is nothing wrong with this approach.

like image 88
Salman A Avatar answered Oct 13 '22 15:10

Salman A


Don't use eval() - it's evil!

Use the relative local path an automatically map it to a absolute URL.

like image 43
Alix Axel Avatar answered Oct 13 '22 14:10

Alix Axel