【问题标题】:fgetcsv only read first line of csv-file (UPDATE: includes solution)fgetcsv 仅读取 csv 文件的第一行(更新:包括解决方案)
【发布时间】:2015-09-05 08:52:29
【问题描述】:

我有以下代码,但效果不佳。它只读取 csv 文件的第一行,为什么?有谁能够帮我?我很沮丧:(

$handle = fopen($_FILES['prof_datei']['tmp_name'], "r");

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $insert_profs_data = $db->prepare("INSERT INTO professoren (name, titel_prof, titel_dr, titel_ing) VALUES (:eins, :zwei, :drei, :vier)");
    $insert_profs_data->bindParam(':eins', $data[0]);
    $insert_profs_data->bindParam(':zwei', $data[1]);
    $insert_profs_data->bindParam(':drei', $data[2]);
    $insert_profs_data->bindParam(':vier', $data[3]);
    $insert_profs_data->execute();
}

fclose($handle);

UPDATE 解决方案:如果您使用mac 执行此代码,则应在打开文件之前添加以下代码行:

ini_set('auto_detect_line_endings', true);

【问题讨论】:

  • 请。添加 CSV 的前 10 行,以便我们为您提供帮助
  • 可能是因为$_FILES['prof_datei']['tmp_name']中的文件是一个临时文件,这个脚本完成后会被删除。可能 MySQL 扩展中的某些内容让 PHP 认为脚本已完成,然后 PHP 会删除该文件。尝试将其移动到真实文件中,对其进行处理,然后将其删除。
  • PHP 文档中fgetcsv() 的一个重要说明是:Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.
  • 谢谢!有用!!! :) :) 我将编辑我的第一个代码 :)

标签: php mysql csv pdo fgetcsv


【解决方案1】:

根据 Mark Ba​​ker 和 johny 的 cmets 发布答案。

在 Mac (OS X) 和可能使用不同行尾的其他操作系统上,您可以在读取文件之前将 auto_detect_line_endings 设置为 true。

ini_set('auto_detect_line_endings', true);
$contents = file('unknowntype.txt');

这应该可以解决 PHP 只读取文件第一行的问题。

【讨论】:

    猜你喜欢
    • 2016-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-16
    • 1970-01-01
    相关资源
    最近更新 更多