将 CSV 文件导入 Postgre

Rus*_*rio 5 php csv postgresql

我正在编写一些 PHP 代码以将 CSV 文件导入 Postgre DB,但出现以下错误。你能帮助我吗?

警告:pg_end_copy():查询失败:错误:在数据中找到文字换行符提示:使用“\n”表示换行符。上下文:复制 t_translation,C:\xampp\htdocs\importing_csv\importcsv.php 中的第 2 行,第 21 行

<?php
$connString = 'host = localhost dbname= importdb user=postgres password=pgsql';
$db = pg_connect($connString);

$file = file('translation.csv');

//pg_exec($db, "CREATE TABLE t_translation (id numeric, identifier char(100), device char(10), page char(40), english char(100), date_created char(30), date_modified char(30), created_by char(30), modified_by char(30) )");
pg_exec($db, "COPY t_translation FROM stdin");


foreach ($file as $line) {

    $tmp = explode(",", $line);

    pg_put_line($db, sprintf("%d\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n", $tmp[0], $tmp[1], $tmp[2], $tmp[3], $tmp[4], $tmp[5], $tmp[6], $tmp[7], $tmp[8]));

}

pg_put_line($db, "\\.\n");
pg_end_copy($db);
?>
Run Code Online (Sandbox Code Playgroud)

小智 3

您需要在函数FILE_IGNORE_NEW_LINES中指定标志file()作为第二个参数,否则默认情况下将在每个数组项的末尾包含换行符。这可能是导致这里问题的原因。

因此,只需添加此标志,FILE_IGNORE_NEW_LINES以便从 csv 文件中提取的行在每行末尾不会有换行符:

$file = file('translation.csv', FILE_IGNORE_NEW_LINES);
Run Code Online (Sandbox Code Playgroud)

另外我建议使用fgetcsv()来读取 csv 文件。