PHP注意:从.csv导入时出现未定义的偏移量错误 [英] PHP Notice: Undefined offset error when importing from .csv

查看:108
本文介绍了PHP注意:从.csv导入时出现未定义的偏移量错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码从csv导入数据时,我不断收到上述错误:

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);

数据按预期方式导入,但由于我们在多个php脚本中使用相同的代码,因此错误日志正在填满.错误在以下行:

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);

尝试使用以下建议: php上的未定义偏移量错误导入CSV 无济于事,以及网站上的其他内容.

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.

推荐答案

由于list()试图分配两个变量,因此它试图访问两个数组元素[0][1].因为该行上没有逗号,所以[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.

尝试一些不同的功能:

$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];
}

这篇关于PHP注意:从.csv导入时出现未定义的偏移量错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆