PHP CSV到数组 - 当一个为空时继续读取字段

I got like this CSV:

1|bla.jpg|nature
2|       |earth

When I convert the CSV to array like this:

while (($line = fgetcsv($handle, 1000, ';')) !== FALSE)
{
    $data[] = $line;
}

then I get follow array in $data:

array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(7) "bla.jpg"
    [2]=>
    string(6) "nature"
  }
  [1]=>
  array(1) {
    [0]=>
    string(163) "2"
  }
}

But I need it like that:

array(2) {
  [0]=>
  array(3) {
    [0]=>
    string(1) "1"
    [1]=>
    string(7) "bla.jpg"
    [2]=>
    string(6) "nature"
  }
  [1]=>
  array(3) {
    [0]=>
    string(1) "2"
    [1]=>
    string(0) ""
    [2]=>
    string(5) "earth"
  }
}

How can I keep parsing CSV when one field is empty?

Ignore it: I need to add some more text -.-

Use file() to read it as an array, then explode each line with ";".

// For demo purpose
$str = "1;bla.jpg;nature
        2;;earth";
$arr = explode(PHP_EOL, $str);
// End
// $arr = file("file.csv");

Foreach($arr as &$line) $line = explode(";", $line);

Var_dump($arr);

https://3v4l.org/9FdVQ

Since it was unclear.

$arr = file("file.csv");

Foreach(array_splice($arr,0,10) as &$line) $line = explode(";", $line);

Var_dump($arr);

Maybe don't use fgetcsv, but read the entire line and use explode(';', $line) to split the line on each comma (or any other suitable delimiter ; csv files usually use ; but can also use , or tab)

Set correct delimeter

while (($line = fgetcsv($handle, 1000, '|')) !== FALSE)

demo

For me this code works as expected,

you should try:

  • read another CSV file

  • check the encoding of CSV file is proper (I suppose it should be a UTF-8 encoding)

  • check, that delimiters in the file are the same like in the code

Look into php docs: http://php.net/manual/en/function.fgetcsv.php

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.

Maybe this problem is related to operating system, which was used to create this CSV file?