read files

In this part of the PHP tutorial, you will learn how to do file operations with PHP. This article is about reading files, in the next article about writing files.

Read Files using file_get_contents()

The easiest way to read a file is by using the function file_get_contents ($ filename), For example, create a text file in your folder, eg a file quitate.txt in which you write your favorite quotes, one quote per line.

You can now read in and output this quotes.txt in PHP as follows:

$quotes= file_get_contents('quotes.txt');
echo $quotes;

The file_get_contents() function reads in the specified file and returns all its contents. This content is then stored in the variable $quotes.

If you call the above script, you will notice that all quotes appear in a line in your browser. The line breaks have disappeared. This is because the output from the browser is interpreted as HTML code and you have to use your <br> or <br /> for a line break. For example, you could put a <br /> in your text file at the end of every line, and each quote will be printed on its own line.

The other option is to use PHP to convert all line breaks into HTML line breaks. For this purpose the function nl2br() exists in PHP which converts new lines to HTML line breaks ( <br /> ). The customized code looks like this:

$quotes = file_get_contents('quotes.txt');
echo nl2br($quotes);

Read files line by line using file ()

With file_get_contents () we were able to read and output the entire contents of a file. However, it is often advisable to read in a file line by line. In the example above, there is one quote per line in quotes.txt. Maybe we would like to spend a random quote in our application or spend all citations numbered.

To read a file line by line, we can use the file function. This will read the file and save each line as an array element:

$quotes= file("quotes.txt");
for($i=0;$i < count($quotes); $i++){
   echo $i.": ".$quotes[$i]."<br><br>";

In the above script, we first output the serial number $i (starting from 0), followed by a space, then the quote and finally an HTML line break.

If you happen to want to quote, the PHP function rand($ min, $ max) at. This function specifies a random number between $min and $max. The code that returns a random quote on every call looks like this:

$quotes = file ("quotes.txt");
$quote_number = rand (0, count ($citations) -1);
echo $quotes [$quote_number];

Using rand (0, count ($ quotes)); we get a random number between 0 and the total number of quotes stored in the variable $quotes.

How useful was this post?

Click on a star to rate it!

Average rating / 5. Vote count:

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!