PHP Problems with Bars

Asked

Viewed 289 times

0

Guys I did some research but I couldn’t find anything assertive about the mistake I’m having. I’m inserting a csv file into the database, but the backslash has bugged the column separation too much, a data from the c column joins with the b column.

Follows code;

PHP

<?php
$file = "arquivo.csv"
if (($base = fopen($file, "r")) !== FALSE) {
  while (($data = fgetcsv($base, 0, ";")) !== FALSE) {
   //aqui realizo as correções de campos e insert na base utilizando $data[0], $data[1]...e assim por diante.
  }
}

RESULT WITH ERROR

The failure happens with some records in specific. The return of $sql is something like that:

INSERT INTO (coluna1, coluna2, coluna3, coluna4, coluna5)
VALUES ("13", "asuahsuhas /";1435789;Nome do Usuario"","")

An example field that is giving error:

Uheuehuehwueheue /\

It seems to me that the backslash breaks the tab, and so I understood there would be a need to fix this in reading the file and not via replace. *NOTE: I cannot move file base . csv

Any hint ?

  • I’m not sure, but I think this can be solved by putting a backslash before this bar, so: "asuahsuhas \/", should be possible using the str_replace

  • But replace doesn’t change the fact that php read 3 fields in 1 only I needed to fix in reading the file, but I don’t know how.

  • I saw that the fgetcsv has an escape $escape = "" but I still can’t understand the use

  • there is a difference between bars, the "" is a, say, special character, it lets 'escape'(printar) other characters that special, as in regex, if you want to catch a parentheses without it being used to limit a group, whereas the other bar is a common character, Which one do you have on your CSV? if you have "", you should change this exhaust to some).

  • an example is if you have a " t" in your file, it will skip a line. http://php.net/manual/regexp.reference.escape.php

  • in csv comes bar "/" and the inverted "" are breaking the columns

Show 1 more comment

1 answer

0


I could not understand how it works, but replacing fgetcsv with the data below solved:

($data = fgetcsv($base, 0, ';' , '"' , '"')

So reading the csv file does not break, after that I just overwritten the bars.

<?php
  $file = "arquivo.csv"
  if (($base = fopen($file, "r")) !== FALSE) {

     while (($data = fgetcsv($base, 0, ';' , '"' , '"')) !== FALSE) {
       $data = str_replace('/', '', $data);
       $data = str_replace('\\', '', $data);
       //aqui realizo as correções de campos e insert na base utilizando $data[0], $data[1]...e assim por diante.
     }
  }

Settled by then.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.