【问题标题】:How to show randomly generated text and image from a .txt file?如何显示 .txt 文件中随机生成的文本和图像?
【发布时间】:2018-12-14 16:35:40
【问题描述】:

这是我的代码,它从输入字段中的 random.txt 文件生成随机文本。

<?php
 //Path of file
 $myFile = "random.txt";
 //Read file from array
 $lines = file($myFile);
 //Get number line of file
 $lineTotal = count($lines);
 //Remove 1 line (start from 0)
 $count = $lineTotal-1;
 //Get casual number
 $number_casual = rand(0,$count);
 //Print line 2 ([0] = 1 ; [1] = 2 ; ...)
?>
<input name="accesspin" style="width: 300px" value="<?php echo htmlentities( $lines[$number_casual] ); ?>" size="36">

这是random.txt 文件:

USA
UK
Canada

我想在输入框上方显示随机图片:

<img src="A random pic"alt="Flags" height="42"width="42">

<input name="accesspin" style="width: 300px" value="<?php echo htmlentities( $lines[$number_casual] ); ?>" size="36">

random.txt 看起来像这样:

us_flag.jpg
USA
uk_flag.jpg
UK
ca_flag.jpg
Canada

我希望此 PHP 代码在输入字段上方随机显示国旗图片,并在 txt 文件中的国旗图片文件名下方显示国家名称以显示在输入字段内。

【问题讨论】:

  • 旁注:您为什么不为此使用数据库有什么特别的原因吗?它比处理文本文件要简单得多。
  • @FunkFortyNiner 我从没用过数据库
  • 我会避免使用.txt 文件...要么使用数据库,要么使用更结构化的东西,例如.json.xml 文件。
  • 嗯,几年前我也做过同样的事情,很高兴我主动学习如何使用数据库,这让事情变得容易多了:) @user8481790

标签: php file random


【解决方案1】:
<?php
 srand(time(null));
 //Path of file
 $myFile = "random.txt";
 //Read file from array
 $lines = file($myFile);
 //Get number line of file
 $lineTotal = count($lines);
 //Remove 1 line (start from 0)
 $count = $lineTotal-1;
 //Get casual number
 $number_casual = rand(0,$count);
 if($number_casual%2==0){
    $value = htmlentities( $lines[$number_casual+1] );
    $image = htmlentities( $lines[$number_casual] );
 }else{
    $value = htmlentities( $lines[$number_casual] );
    $image = htmlentities( $lines[$number_casual-1] );
 }
 //Print line 2 ([0] = 1 ; [1] = 2 ; ...)
?>
<input name="accesspin" style="width: 300px" value="<?php echo $value; ?>" size="36">
<img src="<?php echo $image; ?>"alt="Flags" height="42"width="42">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    相关资源
    最近更新 更多