fgetcsv

(PHP 4, PHP 5, PHP 7, PHP 8)

fgetcsv从文件指针中读入一行并解析 CSV 字段

说明

fgetcsv(
    resource $stream,
    ?int $length = null,
    string $separator = ",",
    string $enclosure = "\"",
    string $escape = "\\"
): array|false

fgets() 类似,只除了 fgetcsv() 解析读入的行并找出 CSV 格式的字段然后返回一个包含这些字段的数组。

注意:

使用此函数需要考虑区域设置。例如,如果 LC_CTYPEen_US.UTF-8,通过该函数可能会导致对文件中的单字节编码读取错误。

参数

stream

一个由 fopen()popen()fsockopen() 产生的有效文件指针。

length

必须大于在 CVS 文件(允许尾随行尾字符)中找到的最长行(以字符为单位)。否则,该行将拆分为 length 字符的块,除非拆分发生在环绕字符内。

忽略此参数(或者设为 0 或者在 PHP 8.0.0 及以后的版本中设为 null)行的最大长度将不受限制,速度稍慢。

separator

可选的 separator 参数,设置字段分隔符(仅一个单字节字符)。

enclosure

可选的 enclosure 参数,设置字段环绕符(仅一个单字节字符)。

escape

可选的 escape 参数,设置转义字符(最多一个单字节字符)。空字符串("")禁用所有的转义机制。

注意: Usually an enclosure character is escaped inside a field by doubling it; however, the escape character can be used as an alternative. So for the default parameter values "" and \" have the same meaning. Other than allowing to escape the enclosure character the escape character has no special meaning; it isn't even meant to escape itself.

返回值

成功时返回包含读取字段的索引数组, 或者在失败时返回 false

注意:

CSV 文件中的空行将被返回为一个包含有单个 null 字段的数组,不会被当成错误。

注意: 在读取在 Macintosh 电脑中或由其创建的文件时, 如果 PHP 不能正确的识别行结束符,启用运行时配置可选项 auto_detect_line_endings 也许可以解决此问题。

更新日志

版本 说明
8.0.0 现在 length 允许为 null.
7.4.0 escape 参数也接受空字符串来禁用所有的转义机制。

范例

示例 #1 读取并显示 CSV 文件的整个内容

<?php
$row
= 1;
if ((
$handle = fopen("test.csv", "r")) !== FALSE) {
while ((
$data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo
"<p> $num fields in line $row: <br /></p>\n";
$row++;
for (
$c=0; $c < $num; $c++) {
echo
$data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>

参见

  • str_getcsv() - 解析 CSV 字符串为一个数组
  • explode() - 使用一个字符串分割另一个字符串
  • file() - 把整个文件读入一个数组中
  • pack() - 将数据打包成二进制字符串
  • fputcsv() - 将行格式化为 CSV 并写入文件指针

add a note

User Contributed Notes

There are no user contributed notes for this page.
To Top