shqnks shqnks - 1 year ago 125
PHP Question

Using a "#" Separator in fgetcsv?

I used the http://php.net/manual/fr/function.fgetcsv.php Documentation to use the fgetcsv function in order to import a csv file in my database (my server doesn't allows me to use the LOAD DATA INFILE sql function).

But my CSV files contains "#" character line separators and not a \n

I don't know how to make fgetcsv know that this is the line separator...

Here is my code:

$file = fopen("Contenu/BD/test.csv", "r");
fgetcsv($file);
while(($data = fgetcsv($file, 10000, ";")) !== FALSE){
$num = count($data);
for ($c=0; $c<$num; $c++){
$col[$c] = $data[$c];
}

((INSERT SQL))

}
fclose($file);


Thanks a lot for your answers!

Answer Source

But my CSV files contains "#" character line separators and not a \n

Then this is not valid CSV file.

I don't know how to make fgetcsv know that this is the line separator...

No, because this is not a valid line separator. You should make it valid CSV by replacing all these # with \n prior parsing.

*EDIT**

Then you either do 2 step import -> convert # to LFs and then use fgetcsv() or you can try to use str_getcvs() instead, however that would require to read and keep whole input file in memory as you still will need to break the data into separate rows (i.e. with explode()).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download