Current Location: Home> Function Categories> fgetcsv

fgetcsv

Read a line from the file pointer and parse the CSV field
Name:fgetcsv
Category:File system
Programming Language:php
One-line Description:Parses a line from the open file and verify the CSV field.

Definition and usage

The fgetcsv() function reads a line from the file pointer and parses the CSV field.

Similar to fgets() , the difference is that fgetcsv() parses the read lines and finds fields in CSV format, and then returns an array containing these fields.

FALSE is returned when fgetcsv() error occurs, including when the file ends.

Note: Since PHP 4.3.5, the operation of fgetcsv() is binary safe.

Example

Example 1

 <?php

$file = fopen ( "contacts.csv" , "r" ) ;
print_r ( fgetcsv ( $file ) ) ;
fclose ( $file ) ;

?>

CSV file:

 George , John , Thomas , USA
James , Adrew , Martin , USA

The output is similar:

 Array 
( 
[0] => George
[1] => John 
[2] => Thomas
[3] => USA
)

Example 2

 <?php

$file = fopen ( "contacts.csv" , "r" ) ;

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

fclose ( $file ) ;

?>

CSV file:

 George , John , Thomas , USA
James , Adrew , Martin , USA

The output is similar:

 Array 
( 
[0] => George
[1] => John 
[2] => Thomas
[3] => USA

Array
(
[0] => James
[1] => Adrew
[2] => Martin
[3] => USA
)

grammar

 fgetcsv ( file , length , separator , enclosure )
parameter describe
file Required. Specify documents to be inspected.
length

Optional. The maximum length of the specified line. Must be greater than the longest line in the CVS file.

This parameter is optional in PHP 5. It is required before PHP 5.

If this parameter is ignored (set to 0 in PHP 5.0.4 and later), then there is no limit on the length, but it may affect execution efficiency.

separator Optional. Sets the field delimiter (only one character is allowed), the default value is comma.
enclosure

Optional. Sets the field surround character (only one character is allowed), with the default value being double quotes.

This parameter was added in PHP 4.3.0.

Similar Functions
  • Test whether the file pointer reaches the end of the file feof

    feof

    Testwhetherthefilepo
  • See unlink() or unset() (PHP does not have delete keywords or functions) delete

    delete

    Seeunlink()orunset()
  • Write to files (safely used in binary files) fwrite

    fwrite

    Writetofiles(safelyu
  • Provide information about the document stat

    stat

    Provideinformationab
  • Get the inode modification time of the file filectime

    filectime

    Gettheinodemodificat
  • Get the file owner fileowner

    fileowner

    Getthefileowner
  • Determine whether the given file name is a normal file is_file

    is_file

    Determinewhethertheg
  • Determine whether the given file name is writable is_writable

    is_writable

    Determinewhethertheg
Popular Articles