注意:未定义的偏移量:2,同时使用php从csv获取数据

注意:未定义的偏移量:2,同时使用php从csv获取数据

问题描述:

I was trying to fetch the data from csv to display using php.Here is the code

<?PHP

    $file_handle = fopen("dept.csv", "r");

    while (!feof($file_handle) ) {

        $line_of_text = fgetcsv($file_handle, 1024);
        print ($line_of_text[0]) . "   ". ($line_of_text[1]). ($line_of_text[2]) . "<BR>";

    }

    fclose($file_handle);

?>

I am getting the output but getting a notice msg :

Notice: Undefined offset: 2

How to solve it?

  1. You don't post such questions without providing the file
  2. Appears that there are either only 2 columns in csv file or 1 of the entries does not have the third column filled in
  3. If you don't want to look into the file you can do this:

    $file_handle = fopen("dept.csv", "r");
    
    while (!feof($file_handle) ) {
    
        $line_of_text = fgetcsv($file_handle, 1024);
        print ($line_of_text[0]) . "   ". ($line_of_text[1]);
        if (isset($line_of_text[2]))
             print($line_of_text[2]);
        print ("<BR>");
    
    }
    
    fclose($file_handle);