Latest web development tutorials

PHP fgetcsv () function

PHP Filesystem Reference Manual Complete PHP Filesystem Reference Manual

Definition and Usage

fgetcsv () function parses a line from an open field calibration CSV file.

fgetcsv () function when it reaches the end of a specified length or read file (EOF) (whichever comes first), Stop to return to a new line.

If successful, the function returns an array of places CSV fields, or if it fails to reach the end of the file (EOF) returns FALSE.

grammar

fgetcsv(file,length,separator,enclosure)

参数 描述
file 必需。规定要检查的文件。
length 可选。规定行的最大长度。必须大于 CSV 文件内最长的一行。如果忽略该参数(或者设置为 0),那么行长度就没有限制,不过可能会影响执行效率。

注意:该参数在 PHP 5 之前的版本是必需的。

separator 可选。设置字段分界符(只允许一个字符),默认值为逗号( , )。
enclosure 可选。设置字段环绕符(只允许一个字符),默认值为双引号( " )。


Tips and Notes

Tip: See fputcsv () function.


Example 1

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

CSV file:

Kai Jim, Refsnes, Stavanger, Norway
Hege, Refsnes, Stavanger, Norway

The code above will output:

Array
(
[0] => Kai Jim
[1] => Refsnes
[2] => Stavanger
[3] => Norway
)


Example 2

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

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

fclose($file);
?>

CSV file:

Kai Jim, Refsnes, Stavanger, Norway
Hege, Refsnes, Stavanger, Norway

The code above will output:

Array
(
[0] => Kai Jim
[1] => Refsnes
[2] => Stavanger
[3] => Norway
)
Array
(
[0] => Hege
[1] => Refsnes
[2] => Stavanger
[3] => Norway
)


PHP Filesystem Reference Manual Complete PHP Filesystem Reference Manual