ZetCode

PHP fgetcsv 函数

最后修改于 2025 年 4 月 3 日

PHP fgetcsv 函数从文件指针读取一行并将其解析为 CSV 数据。对于处理逗号分隔值文件至关重要。

基本定义

fgetcsv 函数将打开文件的一行解析为 CSV 格式。它返回一个包含读取的字段的数组,或在失败时返回 false。

语法: fgetcsv(resource $stream, int $length = 0, string $separator = ",", string $enclosure = '"', string $escape = "\\"): array|false。该函数可以处理各种 CSV 格式,并具有可自定义的定界符。

基本 fgetcsv 示例

这展示了 fgetcsv 读取 CSV 文件的最简单用法。

basic_fgetcsv.php
<?php

declare(strict_types=1);

$file = fopen('data.csv', 'r');

if ($file !== false) {
    while (($row = fgetcsv($file)) !== false) {
        print_r($row);
    }
    fclose($file);
}

这会读取并解析 data.csv 的每一行数据。每一行都会成为一个数字索引的数组。该函数会自动处理带引号的字段和逗号。

自定义分隔符示例

fgetcsv 可以处理不同的字段分隔符,而不仅仅是逗号。

custom_delimiter.php
<?php

declare(strict_types=1);

$file = fopen('pipe_delimited.txt', 'r');

if ($file !== false) {
    while (($row = fgetcsv($file, 0, '|')) !== false) {
        print_r($row);
    }
    fclose($file);
}

在这里,我们通过指定 '|' 作为分隔符来解析管道分隔的文件。第二个参数 (0) 表示没有长度限制。其他常见的定界符包括制表符。

处理标题

本示例演示了如何读取带有标题的 CSV 文件并处理数据行。

csv_with_headers.php
<?php

declare(strict_types=1);

$file = fopen('users.csv', 'r');

if ($file !== false) {
    $headers = fgetcsv($file);
    
    while (($data = fgetcsv($file)) !== false) {
        $row = array_combine($headers, $data);
        print_r($row);
    }
    fclose($file);
}

我们首先读取标题行,然后使用 array_combine 将其与每个数据行结合。这会创建以标题名称作为键的关联数组。

自定义包围字符

这展示了如何处理具有不同包围字符的 CSV 文件。

custom_enclosure.php
<?php

declare(strict_types=1);

$file = fopen('quoted_data.csv', 'r');

if ($file !== false) {
    while (($row = fgetcsv($file, 0, ',', "'")) !== false) {
        print_r($row);
    }
    fclose($file);
}

在这里,我们将单引号指定为包围字符,而不是默认的双引号。这对于字段被单引号包围的文件很有用。

处理大型文件

本示例演示了如何以内存高效的方式处理大型 CSV 文件。

large_file_processing.php
<?php

declare(strict_types=1);

function processLargeCsv(string $filename): void {
    $file = fopen($filename, 'r');
    
    if ($file === false) {
        throw new RuntimeException("Failed to open file: $filename");
    }

    try {
        while (($row = fgetcsv($file)) !== false) {
            // Process each row without loading entire file
            processRow($row);
        }
    } finally {
        fclose($file);
    }
}

function processRow(array $row): void {
    // Implementation of row processing
    echo implode(', ', $row) . PHP_EOL;
}

这种方法一次读取和处理一行,使其对于大型文件具有内存效率。try-finally 块确保文件句柄始终被关闭。

边缘情况

fgetcsv 在各种边缘情况下具有特定的行为。

edge_cases.php
<?php

declare(strict_types=1);

$file = fopen('edge_cases.csv', 'r');

if ($file !== false) {
    // Empty line
    $empty = fgetcsv($file);
    
    // Line with only delimiters
    $delims = fgetcsv($file);
    
    // Quoted fields with embedded delimiters
    $quoted = fgetcsv($file);
    
    print_r($empty);   // array(1) { [0]=> NULL }
    print_r($delims);  // array with empty strings
    print_r($quoted);  // properly parsed fields
    
    fclose($file);
}

空行返回一个包含单个 NULL 元素的数组。仅包含定界符的行返回空字符串。带引号字段中的嵌入定界符会被正确处理。

最佳实践

来源

PHP fgetcsv 文档

本教程通过实际示例介绍了 PHP fgetcsv 函数,展示了其在不同 CSV 处理场景中的用法。

作者

我叫 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在教学编程方面拥有十多年的经验。

列出 所有 PHP 文件系统函数