【问题标题】:fgetcsv brings all data in the first linefgetcsv 在第一行带来所有数据
【发布时间】:2015-08-09 17:42:11
【问题描述】:

使用 fgetcsv 是我发现读取系统所需的 csv 文件的选项。但它似乎并非每次都有效(实际上,这段代码有效时非常罕见)。

if (($handle = fopen($file, 'r')) !== FALSE) {
    set_time_limit(0); // necessary if a large csv file

    $row = 0;
    while (($data = fgetcsv($handle, 0, ',')) !== FALSE) {
        print_r($data);
        // .. here I do some stuff with the data
        // .. The result should be an array with 5 columns and it run multiple times (for the amount of lines in the file)
        // .. The result however is one array with a over 9000 columns (really over 9000, it's 9489 in the file that I'm testing)
    }
    fclose($handle);
    die();
}

我试图通过在代码之前调用它来检查行尾,但没有成功。

ini_set('auto_detect_line_endings', true);

该文件是由客户端由另一个程序导出的,我不能让它“更新”以适应软件的需要。有没有办法处理 csv 上的这个 encoding/line-ending 问题?

【问题讨论】:

  • 您查看过原始文件以了解其中的内容吗?也许它是在没有行尾的情况下生成的,或者是一个完全非标准的记录结束字符。

标签: php csv encoding fgetcsv


【解决方案1】:

来自PHP Manual(我知道激进的想法)

长度参数

必须大于 CSV 文件中的最长行(以字符为单位)(允许尾随行尾字符)。在 PHP 5 中成为可选参数。省略此参数(或在 PHP 5.1.0 及更高版本中将其设置为 0)最大行长不受限制,速度稍慢。

我不知道您使用的是什么版本的 PHP,但尝试将参数设置为合理的值,您应该开始一次获取一行。

例如

while (($data = fgetcsv($handle, 4096, ',')) !== FALSE) {

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 1970-01-01
    相关资源
    最近更新 更多