【发布时间】: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. -
谢谢!有用!!! :) :) 我将编辑我的第一个代码 :)