php 从 TXT 文件中提取随机行作为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5904045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 22:50:01  来源:igfitidea点击:

Pull random line from TXT file as string

phptextrandom

提问by Ryan Cooper

I'm currently using the code below to try and read a random line from random.txtand pass it as $data, however it comes back empty. Each string has its own line, am I missing something here? Shouldn't this work? If not how can I get a random line from my text file and use it as my $datastring?

我目前正在使用下面的代码尝试从中读取随机行random.txt并将其作为 传递$data,但它返回空。每个字符串都有自己的行,我在这里遗漏了什么吗?这不应该工作吗?如果不是,我怎样才能从我的文本文件中随机获取一行并将其用作我的$data字符串?

$f_contents = file("random.txt");
$line = $f_contents[array_rand($f_contents)];
$data = $line;

Solved - Bad CHMODThought I had double checked it, sorry to post a question.

已解决 - 错误的 CHMOD以为我已经仔细检查过了,很抱歉提出问题。

采纳答案by shmeeps

Make sure your file has read permissions set, should be CHMOD'd to 644 or 744.

确保您的文件设置了读取权限,应该 CHMOD 为 644 或 744。

回答by Sitnik

Your code looks correct, but you can try it this way too:

您的代码看起来是正确的,但您也可以这样尝试:

<?php
    $f_contents = file("random.txt"); 
    $line = $f_contents[rand(0, count($f_contents) - 1)];
?>