I want to import a CSV file into my Postgresql database through a PHP page. Is there a way to preprocess the CSV file so as to remove the trailing whitespace other than writing to the database line by line?
Asked
Active
Viewed 590 times
1
-
sed will work just fine. – wildplasser Oct 29 '16 at 13:23
-
@wildplasser could you please explain a little bit more? – M_T Oct 29 '16 at 13:27
-
on unix: `man sed` you need something like `sed 's/[ \t\r]*$//'
outfile.csv` – wildplasser Oct 29 '16 at 13:57 -
thanks. is there a solution for windows as well? – M_T Oct 29 '16 at 14:01
-
1Windows was never intended to do actual programming. – wildplasser Oct 29 '16 at 15:12
-
Several ways of getting sed under Windows: http://stackoverflow.com/questions/127318/is-there-any-sed-like-utility-for-cmd-exe#127567 – mlinth Oct 29 '16 at 16:43
-
thanks I'll check it out @mlinth – M_T Oct 29 '16 at 17:34
1 Answers
0
Since you already import the data with PHP, you can employ it for preparing the file as well. See trim
for removing whitespace at both ends, or rtrim
for trailing whitespace.
A simple loop does the job
$fp = fopen('/path/to/file.csv', 'r');
$tmp = fopen('/path/to/tmpfile.csv', 'w');
while (($line = fgets($fp)) !== false) {
$line = rtrim($line);
fwrite($tmp, $line);
}
fclose($tmp);
fclose($fp);
// now you can import /path/to/tmpfile.csv

Olaf Dietsche
- 72,253
- 8
- 102
- 198