Roman
Roman

Reputation: 19

SplFileObject's fgetcsv method reads \" as part of the text and not as a cell end character

I ran into a problem that SplFileObject's fgetcsv method reads \" as part of the text and not as a cell end character

Example:

File:

;12;012345678;"foo\";1;"100 000 000;"
;13;012345679;"bar";1;"100 000 000;"

Output:

(
    [0] => 
    [1] => 12
    [2] => 012345678
    [3] => foo\";1;100 000 000
    [4] => 
;13;012345679;bar"
    [5] => 1
    [6] => 100 000 000;
)

Code:

$file = new SplFileObject('1.txt');
$file->openFile();
$file->setCsvControl(';');
while ($str = $file->fgetcsv()) {
    print_r($str);
}

Tell me, please, is it possible to force fgetcsv not to read "\" as escaping?

Upvotes: -1

Views: 34

Answers (1)

Fravadona
Fravadona

Reputation: 17208

From https://www.php.net/manual/en/splfileobject.setcsvcontrol.php :

public SplFileObject::setCsvControl(
    string $separator = ",",
    string $enclosure = "\"",
    string $escape = "\\"
): void

If your SCSV has standard CSV escaping rules then you should use:

$file->setCsvControl(';', "\"", "\"");

Upvotes: 2

Related Questions