pTutorial

New way to learn PHP

PHP 5 File more fuction | read function

fgets function

fgets function is used to read the string from the file pointed to by the file pointer. The file pointer must point to an opened file that is readable. It stop freading when a new line read or an end of file (EOF) read.

Syntax of fopen

string fgets (int filepointer, int length);

Example

<?php

$fh = fopen( "pt.txt", "r" );
$line = fgets( $fh );
echo $line;
fclose( $fh );

?>

output

Mr brownMr victor

You can read all the data of opened file using loops as shown in below example.

Example

<?php

$fh = fopen( "pt.txt", "r" );
while ( $line = fgets( $fh ) ) {
echo $line."
"; } fclose( $fh ); ?>

Read all data in the form of string

You can use file_get_contents function to read all the data of file without open the file. It return true if successfully read otherwise return false.

Syntax

file_get_contents("file_name");

Note: There is no need to open or close the file beacuse its works directly without open the file.

Example

<?php

$data = file_get_contents("pt.txt");
echo $data;

?>

Read CSV file or Excel file

You can use file_get_contents function to read all the data of file without open the file. It return true if successfully read otherwise return false.

Syntax

fgetcsv(file_name,length,separator,enclosure);

It takes four argument but only file_name is mandatry other three are optional.

Example

<?php

$fh = fopen( "uk3.csv", "r" );
while ( $data = fgetcsv( $fh, 1000 ) ) 
{

echo "{$data[0]} {$data[1]}
"; } fclose( $fh ); ?>

Output

name Age
John 45
Anna 37
Bill 32

QUOTES OF THE DAY

Beauty is truth, Truth beauty- That is all

LIKE ON FACEBOOK

+1 ON GOOGLE

SHARE ON TWITTER