2

I'm trying to make (as immature as this sounds) an application online that prints random insults. I have a list that is 140 lines long, and I would like to print one entire line. There is mt_rand(min,max) but when I use that alongside fgets(file, "line") It doesn't give me the line of the random number, it gives me the character. Any help? I have all the code so far below.

<?php
$file = fopen("Insults.txt","r");
echo fgets($file, (mt_rand(1, 140)));
fclose($file);
?>
4

4 回答 4

1

试试这个,这是你想做的更简单的版本:

$file = file('Insults.txt');
echo $file[array_rand($file)];
于 2013-06-02T22:11:44.163 回答
0

首先:您完全正确地使用了 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);

(未经测试!)

于 2013-06-03T14:27:56.337 回答
0
$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;
于 2013-06-02T22:11:41.793 回答
0

用于file()此。它返回一个包含文件行的数组:

$lines = file($filename);
$line = mt_rand(0, count($lines));   

echo $lines[$line];
于 2013-06-02T22:12:18.533 回答