检查文本文件中的行是否为空

时间:2016-06-29 19:33:35

标签: php

我正在解析文本文件,需要忽略空行/空行。

文字档案:

00, Item one
01, Item two
02, Item three

03, Item four
04, Item five

05, Item six

PHP

// get the file contents
$file_contents = fopen($file["tmp_name"], "r");

// declare array to hold each line in file
$organizations = array();

// for each line in file
while (!feof($file_contents)) {
    // get current line in file
    $line = fgets($file_contents);

    // if line is empty or blank, skip
    if ($line[0] == "\n") {
        // push line to array
        // this is not being executed for blank / empty lines
        $organizations[] = "empty line...";
    }
    else {
        $organizations[] = $line;
    }
}

以上代码不适用于空行。空/空行仍然被推送到数组,而不是"空行......"字符串。

如何检查线条是否为空/空?

1 个答案:

答案 0 :(得分:0)

// get the file contents

$file_contents = fopen($file["tmp_name"], "r");

// declare array to hold each line in file

$organizations = array();

// for each line in file
while (!feof($file_contents)) {
  // get current line in file
  $line = fgets($file_contents);
  
  // by this method you can detect if line is empty or blank, skip
  if (sizeof(str_split($line)) < 3) {
    // push line to array
    // this is not being executed for blank / empty lines
    $organizations[] = "empty line...";
  }
  else {
    $organizations[] = $line;
  }
}
相关问题