0

\I am generating SQL file from CSV file, but have some string files with slashes and the value is like:

 "aaa", "\", 111, 222, "bbb", "\", 333

The value between "\" will be generated as one string

'\", 111, 222, "bbb", "\', 333

But I hope to keep "\" as it should to be, or change it to NULL, like:

'NULL', 111, 222, 'bbb', 'NULL', 333

My code is like this:

while (($lineArr = fgetcsv($infile))!=FALSE){
foreach($lineArr as $line){
...
if ($line == '\\"')
$line = 'NULL';
...
}
}

This dose not work. I think $line =='\\"' is not correct, but I do not know how to process the whole part between "\".

solution: I first change the array to string to process the '"\"', then change it back to array for further process.

while (($lineArr = fgetcsv($infile))!=FALSE){
$string = implode(",", $lineArr);
    if (strpos($string,',\",')){
        $sKeepSlash = str_replace(',\",', ",NULL,", $string);
        $pLineArr = explode(',', $sKeepSlash);
    }
    foreach($lineArr as $line){
    ...
}
}
zhihong
  • 1,808
  • 2
  • 24
  • 34

2 Answers2

1

Use fputcsv() to write, and fgetcsv() to read.

Found here: Escaping for CSV

Community
  • 1
  • 1
Martijn
  • 15,791
  • 4
  • 36
  • 68
  • My csv file is downloaded from other system, so this means I need first using fputcsv() to create a new csv file and then using fgetcsv() to process it? – zhihong Oct 09 '13 at 10:26
  • You should be able to process it the first run if they provide a valid feed. Try lkooking around for `csv escape` – Martijn Oct 09 '13 at 10:39
0

Find the position for the slashes first. For example, you can user array_keys.

this will return the positions of the markers. You can then use that to combine

$marker_positions = array_keys($array, "marker");
for ($position = $marker_positions[0]+1; $position < $marker_positions[0]; $position++) {
    $single_string .= $array[$position];
}
crafter
  • 6,246
  • 1
  • 34
  • 46