Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 到达文件末尾时的无限循环_Php_Php 5.6 - Fatal编程技术网

Php 到达文件末尾时的无限循环

Php 到达文件末尾时的无限循环,php,php-5.6,Php,Php 5.6,我试图获得一个PHP函数,从文本文件中读取信息并将其作为数组返回。我的函数在文件开始时似乎工作得很好,但是get被卡在文件末尾,或者当这个文件为空时 以下是我的函数和文本文件: function readBook($file) { $book = []; $line = trim(fgets($file)); // Get rid of white lines at start of file while ($line !== false && s

我试图获得一个PHP函数,从文本文件中读取信息并将其作为数组返回。我的函数在文件开始时似乎工作得很好,但是get被卡在文件末尾,或者当这个文件为空时

以下是我的函数和文本文件:

function readBook($file) {
    $book = [];
    $line = trim(fgets($file));
    // Get rid of white lines at start of file
    while ($line !== false && strlen($line) === 0) {
      $line = trim(fgets($file));
    }
    if ($line === false) {
      return false;
    }
    // Prepare and return the array
    while ($line !== false && strlen($line) > 0) {
      $pos = strpos($line, ":");
      if ($pos != false) {
        $key = trim(substr($line, 0, $pos));
        $value = trim(substr($line, $pos + 1));
        $book[$key] = $value;
        //echo $line . "\n";
        $line = trim(fgets($file));
      } else {
        throw new \Exception("Erreur - Fichier mal écrit", 125);
      }
    }

    return $book;
  }
文本文件为:

couverture : scorpion.jpg
titre : La marque du diable
serie : Le Scorpion
auteurs : Marini - Desberg
année : 2000
catégorie : bandes-dessinées

couverture : BOB.jpg
titre : La marque du BOB
serie : Le BOB
auteurs : Marini - Desberg
année : 2000
catégorie : bandes-dessinées
在本例中调用函数3次时,它应该只返回两本书。它现在做的是返回两本书,并陷入无限加载循环

你们能帮帮我吗

在EOF时,
trim(fgets($fileHandle))
返回
而不是
false

一开始就改变

$line = trim(fgets($file));
while ($line !== false && strlen($line) === 0) {

$line = fgets($file);
while ($line !== false && strlen(trim($line)) === 0) {
   $line = fgets($file);
}