How To Read A Plain Text As A String Using PHP

Data is commonly stored in text files, whether it be manually entered or exports from a variety of software packages. Data within these text files can be easily extracted and processed with PHP using its native functions.

In this example case, the data within the plain text file will be a list of settings, potentially what could be used within a dashboard or some type of user interface.

The Text File

Here is what the text file contains for the tutorial, it is simply dummy data. The file is named data.txt.

Setting 1
Setting 2
Setting 3
Setting 4
Setting 5

Reading The Text File

Using PHP we need to utilize one of the native functions that open and read the contents of an entire file. This clever function is named file_get_contents()

See the following example which opens the data.txt file and reads the entire contents into a string.

$myfile = file_get_contents("data.txt");

If we print the contents of $myFile it will return a string, see the output below

string(49) "Setting 1 Setting 2 Setting 3 Setting 4 Setting 5"

And that is it!

Posted in PHP

Leave a Reply