从txt文件中获取数据时如何忽略空行

How to ignore blank lines when taking data from txt files

当我从 txt 文件中获取数据时,空行会导致问题

txt文件:

23/04/2021,Ulusal egemenlik ve çocuk bayramı

12/05/2021,Ramazan bayramı 1.gün
13/05/2021,Ramazan bayramı 2.gün
14/05/2021,Ramazan bayramı 3.gün
15/05/2021,Ramazan bayramı 4.gün

函数为:

public static function uploadDataFromFile(){

    $filePath = public_path().'/files/tatiller.txt';
    $read = fopen($filePath,"r",);

    while (!feof($read)){

        $contents = fgets($read);

            $contentArray = explode(",", $contents);

            list($date, $desc) = $contentArray; // ---> Here i taking the ErrorException Undefined offset: 1

            DB::table('holidays')->insert(
                [
                    'date' => $date, 
                    'description' => $desc, 
                    'type' => 0
                ]
            );
        
    }

    fclose($read);
}

如何忽略这些行?

您可以检查该行的长度是否为 0:

if (strlen($contents) == 0) continue;

但是如果你的一行中有空格或者可能只是一个日期,那仍然会失败。检查逗号可能更安全,因为逗号可以更好地指示行中的有效数据:

if (strpos($contents, ',') === false) continue;