PHP Notice: Undefined offset error when importing from .csv [duplicate]

依然范特西╮ 提交于 2019-12-11 18:51:17

问题


I'm continually getting the above error when importing data from csv using the following code:

$csv_data=file_get_contents("data3_received.csv");
foreach(preg_split("/((\r?\n)|(\r\n?))/", $csv_data) as $line){
list($service_id, $ki3) = explode(',', $line,2);

The data imports as expected but the error log is filling up as we utilise the same code in multiple php scripts. The error is on the following line:

list($service_id, $ki3) = explode(',', $line,2);

Tried using the suggestion here: Undefined offset error on php when importing a CSV to no avail, and other on the site.

Any help with this would be most welcome.


回答1:


Since list() is attempting to assign two variables it is attempting to access two array elements [0] and [1]. Because there is no comma on the line, [1] does not exist.

Try some different functions:

$csv_data = file("data3_received.csv", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

foreach($csv_data as $line) {
    $data[] = str_getcsv($line);
}

To get individual variables you need to check if you have more than one column, or something similar:

if(count($data = str_getcsv($line)) > 1) {
    list($service_id, $ki3) = $data;
} else {
    $service_id = $data[0];
}


来源:https://stackoverflow.com/questions/46325515/php-notice-undefined-offset-error-when-importing-from-csv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!