Fri, 17 May 2024


Reading File Contents With PHP

By: Peter, NetArt Media
Wed, 1 August 2018
Reading File Contents With PHP

One of the many reasons I like PHP so much is that it allows for manipulating content in pretty much any context. A person could possibly code out a bunch of URLs from a list by hand, but why bother when simply choosing an option in an HTML form or even just loading a page in a browser can do it for us within seconds?

I have discussed 'fopen' in the past, along with 'fputs' in articles such as Creating CSS Files with PHP. I provide a basic example of using it here, before going on to use the function which I personally prefer when it comes to creating URLs - 'file_get_contents'.

Let's say we have a list of links in a text file called 'file.txt'. Written as so:

Link 1
Link 2
Link 3
Link 4
Link 5
Link 6
Link 7
Link 8
Link 9
Link 10

Using the below code block we can get the file size, as well as return the contents of the txt file in a browser.


This would be the result...

File size : 79 bytes

Link 1
Link 2
Link 3
Link 4
Link 5
Link 6
Link 7
Link 8
Link 9
Link 10

Simple, correct? Indeed. But many sites on the net use something as basic as this for returning the results they desire. As mentioned above though, I prefer using 'file_get_contents' for functions such as reading directories and creating URLs from file contents.


By creating an array with the content from 'file.txt', we then explode it according to line breaks, defining how we would like to return each. I create friendly URLs by lowering the letters, taking out any white space and of course, adding a file extension at the end of the URL. You could add any file extension you wish with an example like this.

Here is the result.

Link 1
Link 2
Link 3
Link 4
Link 5
Link 6
Link 7
Link 8
Link 9
Link 10

It isn't as difficult as you may have thought, huh? With PHP, it usually isn't. Experiment with file reading functions in PHP and see what you can come up with. The possibilities are almost endless.


Category: Web Development
Share this post:



See All Scripts






Subscribe for our newsletter

Receive the latest blog posts direct in your mailbox