如何显示.txt文件中随机生成的文本和图像?

时间:2018-12-14 16:35:40

标签: php file random

这是我的代码,该代码从输入字段内的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文件中在输入字段上方随机显示一个标志图片,并在txt文件中将该标志图片的文件名下的国家/地区名称显示在输入字段内。

1 个答案:

答案 0 :(得分:0)

<?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">