3/31/15

PHP File Open Read


PHP comes with a couple of different ways to read the contents of file.

=> Read the contents using file_get_contents( ) function

The easiest way to read the contents of a disk file with the file_get_contents( ) function.
This function accepts the name and path to a disk file, and read the entire file into a string variable.
Eg i
 <?php
  //read file into string
  $str=file_get_contents('output.txt') or die('ERROR:cannot find the file');
  echo $str;
 ?>

=> Read the contents using file( ) function

An alternative way of reading data from a file is file( ) function, which accepts the name and path to a file and reads the entire file into an array,
with each element of the array representing one line of the file.
Here’s an example which reads a file into an array and then displays it using foreach loop.
Eg ii
 <?php
  //read file into array
  $arr=file('output.txt') or die('ERROR: cannot file file');
  foreach($arr as $line)
  {
  echo $line;
  } 
 ?>

=> Reading remote files contents

All above defined file_get_contents( ) function and file( ) function support reading data from URLs using either the HTTP or FTP protocols.
Here’s an example which reads an HTML file off the Web into an array.
Eg iii
 <?php
  //read file into array
  $arr=file('http://www.google.com') or die('ERROR: cannot file file');
  foreach($arr as $line)
  {
  echo $line;
  } 
 ?>

In case of slow network links, it’s sometimes more efficient to read a remote file in “chunks” to maximize the efficiency of available network bandwidth.

=> Read the contents of the file using fread( ) function

=> Read the contents of the file using fgets( ) function

=> Read the contents of the file using fgetc( ) function



To do this use the fgets( ) function to read a specific number of bytes from a file.
Here’s an example which reads an HTML file using fgets( ) function.
Eg iv
 <?php
  //read file into array chunks
  $fo=fopen('http://www.google.com','r') or die('ERROR: cannot open file');
  while(!feof($fo))
   {
  $str.=fgets($fp,512);  
   }
  echo $str;
  fclose($fo);
 ?>

Read the external PHP file using include( ) or require( ) function

There are 4 functions to include external PHP files.
  1. inculde( )
  2. require( )
  3. inculde_once( )
  4. require_once( )
include( ) function says, a file should be developed which you want to call,
otherwise it shows waring error.
require( ) function says, a file must be developed which you want to call,
otherwise it shows Fatal error.
include_once( ) function says, a file should be called once on a page.
require_once( ) function says, a file must be called once on a page.

0 comments:

Post a Comment

FIND US ON FACEBOOK

FIND US ON Twitter