我试图获得一个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次时,它应该只返回两本书。它现在做的是返回两本书,并陷入无限加载循环。
你们能帮帮我吗?
顺致敬意,