Function explodes that ignores content inside quotes

Asked

Viewed 43 times

1

I’m working on a project in PHP what you need to do import archival CSV, whose separator is by ;. I’m using explode to make the process, but the problem is that in some cases the content may come with ; as in the example below:

principio_ativo              | descricao                              
CIANOCOBALAMINA; DICLOFENACO | 50 MG + 50 MG COM REV CT BL AL PVDC INC

the generated file is as follows:

principio_ativo;descricao
"CIANOCOBALAMINA; DICLOFENACO";50 MG + 50 MG COM REV CT BL AL PVDC INC

 $lines = file($destinationPath.'/'.$result['file']);
 for($i=1; $i<count($lines); $i++){
     $line = $lines[$i];
     $explode = explode(',', $line);
     list($principioAtivo, $apresentacao) = $explode;
 }

//saída:
Array
(
    [0] => "CIANOCOBALAMINA
    [1] =>  DICLOFENACO"
    [2] => 50 MG + 50 MG COM REV CT BL AL PVDC INC
)

//saída ideal:
Array
(
    [0] => "CIANOCOBALAMINA; DICLOFENACO"
    [1] => 50 MG + 50 MG COM REV CT BL AL PVDC INC
)

When using the function explode needed the content that was between " was ignored by explode there is some way to solve this?

At this link I made an example of what happens

1 answer

3


Yes, use the right tools for the job. If you are processing a CSV file, use the function fgetcsv to read the content. Such a function has a parameter that you define string:

fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\" ]]]] ) : array

I mean, just do:

$stream = fopen("arquivo.csv", "r");

while (($data = fgetcsv($stream, 0, ";", '"')) !== false) {
    print_r($data);
}

And so have the return:

Array
(
    [0] => principio_ativo
    [1] => descricao
)
Array
(
    [0] => CIANOCOBALAMINA; DICLOFENACO
    [1] => 50 MG + 50 MG COM REV CT BL AL PVDC INC
)
  • Thank you very much, it worked well!

Browser other questions tagged

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