PHP provides various functions to read data from file:
The fread function is the staple for getting data out of a file.
The function requires a file handle(return by fopen() function), and an integer represents length of byte to be read..
Syntax
string fread (resource $handle , int $length )
Example
data.txt
line 1 line 2 line 3
test.php
<?php // get contents of a file into a string $filename = "D:\\data.txt"; $handle = fopen($filename, "r"); //open file in read mode $contents = fread($handle, filesize($filename)); // read the whole file content echo "<pre>$contents</pre>";//printing contents of the file fclose($handle); // close file ?>
Outputs:
line 1 line 2 line 3
Syntax
string file_get_contents ( string $filename) :
Example
<?php // get contents of a file into a string $filename = "D:\\data.txt"; $contents = file_get_contents($filename); echo "<pre>$contents</pre>";//printing contents of the file ?>
Another method of reading the whole contents from a file is file()
function.
it reads the entire file contents into an array of lines.
<?php $filename = "D:\\data.txt"; // Get a file into an array. $lines = file($filename); // Loop through our array using a foreach loop. foreach ($lines as $line_num => $line) { echo "Line {$line_num} : " . htmlspecialchars($line) . "<br>"; } ?>
Output:
Line 0 : line 1 Line 1 : line 2 Line 2 : line 3 Line 3 : line 4
The PHP fgets() function is used to read single line from the file pointer.
Syntax
string fgets ( resource $handle [, int $length ] )
Example
<?php // Reading a file line by line $filename = "data.txt"; $handle = @fopen($filename, "r"); if ($handle) { while (($buffer = fgets($handle, 4096)) !== false) { echo $buffer; } if (!feof($handle)) { echo "Error: unexpected fgets() fail\n"; } fclose($handle); } ?>
The PHP fgetc() function is used to read single character from the file.
This function is binary-safe.
Syntax
string fgetc ( resource $handle )
Example
<?php // get contents of a file into a string $filename = "data.txt"; $fp = fopen($filename, 'r'); if (!$fp) { echo 'Could not open file '.$filename; } while (false !== ($char = fgetc($fp))) { echo "$char"; } ?>