Search code examples
phpcsvundefinedoffsetexplode

PHP Notice: Undefined offset error when importing from .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);

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.


Solution

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