Skip to content
Advertisement

Import CSV file to Postgre

I’m writing some PHP code to import a CSV file to a Postgre DB, and I’m getting the error below. Can you help me?

Warning: pg_end_copy(): Query failed: ERROR: literal newline found in data HINT: Use “n” to represent newline. CONTEXT: COPY t_translation, line 2 in C:xampphtdocsimporting_csvimportcsv.php on line 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("%dt%st%st%st%st%st%st%st%sn", $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);
?>

Advertisement

Answer

You need to specify FILE_IGNORE_NEW_LINES flag in file() function as a 2nd parameter which otherwise by default will include the newline char at the end of the each array item. This is likely whats causing the issue here.

So just add this flag FILE_IGNORE_NEW_LINES so that lines extracted from csv file will not have newline char at the end of the each line:

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

Also I would recommend using fgetcsv() instead to read csv file.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement