![](/img/trans.png)
[英]Using PHP, how do I echo a line from a text file that starts with a specific value?
[英]How do I choose a specific line from a file?
我正在嘗試制作一個在線打印隨機侮辱的應用程序(聽起來還不成熟)。 我有一個140行長的列表,我想打印一整行。 有mt_rand(min,max)
但是當我將它與fgets(file, "line")
一起使用時,它沒有給我隨機數的行,而是給了我字符。 有什么幫助嗎? 到目前為止,我有所有代碼。
<?php
$file = fopen("Insults.txt","r");
echo fgets($file, (mt_rand(1, 140)));
fclose($file);
?>
試試這個,它是您想要做的事情的簡單版本:
$file = file('Insults.txt');
echo $file[array_rand($file)];
$lines = file("Insults.txt");
echo $lines[array_rand($lines)];
或在函數內:
function random_line($filename) {
$lines = file($filename) ;
return $lines[array_rand($lines)] ;
}
$insult = random_line("Insults.txt");
echo $insult;
為此使用file()
。 它返回一個包含文件行的數組:
$lines = file($filename);
$line = mt_rand(0, count($lines));
echo $lines[$line];
首先:您完全正確地使用了fgets(),請參考手冊中有關第二個參數的含義(顯然不是您認為的那樣)。
第二:file()解決方案將起作用...直到文件大小超過一定大小並耗盡整個PHP內存。 請記住:file()將整個文件讀入數組。
逐行讀取可能會更好,即使那意味着您必須丟棄大部分讀取的數據。
$fp = fopen(...);
$line = 129;
// read (and ignore) the first 128 lines in the file
$i = 1;
while ($i < $line) {
fgets($fp);
$i++;
}
// at last: this is the line we wanted
$theLine = fgets($fp);
(未經測試!)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.