• PHP Video Tutorials

PHP - Function fgetcsv()


Advertisements

The fgetcsv() function can parse a line from an open file and check for CSV fields. This function stops returning on a new line at a specified length or EOF, whichever comes first. This function returns CSV fields in the array on success or false on failure and EOF.

Syntax

array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\\" ]]]] )

This function is similar to fgets() function except that fgetcsv() function parses the line it reads for fields in CSV format and returns an array containing the fields read. The fgetcsv() function can return false on error, including the end of a file.

Example-1

<?php
   $file = fopen("/PhpProject/EmpDetails.csv", "r"); 
   echo fgetcsv($file);
   fclose($file);
?>

Output

Array
(
   [0] => Chandra
   [1] => Ravi
   [2] => Adithya
   [3] => Sai
)

Example-2

<?php
   $file = fopen("/PhpProject/EmpDetails.csv", "r"); 

   while(! feof($file)) {
      print_r(fgetcsv($file));
   }
   fclose($file);
?> 

Output

Array
(
    [0] =>  Chandra
    [1] =>  Ravi
    [2] =>  Adithya
    [3] =>  Sai
)
Array
(
    [0] =>  Dev
    [1] =>  Jai
    [2] =>  Ramesh
    [3] =>  Raja
)
php_function_reference.htm
Advertisements