PHP Lesson 16 – How to Read Files with examples in PHP

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

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:

<?php
$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:

<?php
$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:

<?php
$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:

<?Php
$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.

About The Author

Related posts

Leave a Reply