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 -.-
我有这样的CSV: p>
1 | bla。 JPG |自然\ 2 | | earth
code> pre>
当我将CSV转换为这样的数组时: p>
while(($ line = fgetcsv ($ handle,1000,';'))!== FALSE)
{
$ data [] = $ line;
}
code> pre>
然后 我在 $ data code>中得到了跟随数组: p>
array(2){
[0] =>
array(3){\ n [0] =>
string(1)“1”
[1] =>
string(7)“bla.jpg”
[2] =>
string(6)“ nature“
}
[1] =>
array(1){
[0] =>
string(163)”2“
}
}
code>
但我需要它: p>
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”
}
}
code> pre>
如何保持解析 当一个字段为空时为CSV? p>
忽略它:我需要添加更多文本-.- p>
div>
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);
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)
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?