Below is a standard command in PHP to get contents of a file in a string variable.


Lot of people might wonder why would you get contents of a file in a string if you can get the contents using a simple Include statement.
I would like to add that it is not just about getting the content but also converting the content or processing it as per your requirements.
file_get_contents is a powerful tool and you can do a lot of things with it. I have only listed a few of them which I have tried using in my project.

Evaluating PHP code within the file
I have a CMS environment which does not execute a PHP code. I used the CMS to store my PHP code and used file_get_contents() to get the file contents in a string variable and then execute the file as PHP using the below method.

The above code first converts the file contents in a string and then executes the PHP from it.
Note that the above can also be done by a simple Include statement i.e.
include(“myotherpage”) and that will also execute the PHP code.
So you would wonder what am I achieving through this method?
Converting the file contents to a string variable, you can do a lot of other things as below

Showing all PDF document links with a PDF icon

You can then style the pdf id in a seperate stylesheet.

The above is probably not a good example to show what you can do with file_get_contents

Have a look at the below piece of code.
It will allow you to get content between a set of tags/text.

Furthermore, you can also replace URLs within the file

There are quite a few other cool things you can do with this.
However, note that these snippets of code will be processed every time you load the page. It first converts it to string and then does the processing and finally evaluates it as PHP. This can add a bit of overhead compared to a single Include statement. However, in my project I am using all the above tricks and I don’t see any performance problems and ofcourse you don’t need to convert to string everytime. You can convert the file to string, stack all the statements and then execute the PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *