Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

fgetcsv()

Example

Read and display one line from the open CSV file.

<?php
$file = fopen(“contacts.csv”,“r”);
print_r(fgetcsv($file));
fclose($file);
?>

Definition and Usage

The fgetcsv() function parses a line from an open file and identifies CSV fields.

 

Tip: Also check out the fputcsv() function.

Syntax

fgetcsv(filelengthseparatorenclosure)

Parameter Values

Parameter

Description

file

Mandatory. Specifies the open file from which to read and parse a line.

length

Optional. Defines the maximum length of a line, which should be longer than the longest line (in characters) in the CSV file. If omitted or set to 0, there is no length limit, which may result in slightly slower performance. Note: This parameter was required in versions prior to PHP 5.

separator

Optional. Defines the field separator, with a default of a comma (,).

enclosure

Optional. Defines the field enclosure character, with a default of a double quote (").

escape

Optional. Defines the escape character, with a default of a backslash (\\).

Technical Details

Return Value:

Returns an array with the CSV fields on success, NULL if an invalid file is provided, and FALSE on errors or end-of-file (EOF).

PHP Version:

4.0+

Binary Safe:

Yes, in PHP 4.3.5

PHP Changelog:

PHP 5.3 introduced the escape parameter.

More Examples

Example

Read and display the complete contents of a CSV file.

<?php
$file = fopen(“contacts.csv”,“r”);

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

fclose($file);
?>