【发布时间】:2019-04-28 10:42:54
【问题描述】:
这是我的 php 代码:
<?php
//Path of file
$myFile = "test_file.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 ; ...)
echo $lines[$number_casual];
?>
这个 php 代码从test_file.txt 文件中生成随机文本。
我想在这个输入字段中显示这个 php 代码随机生成的文本:
<input name="accesspin" style="width: 300px" value="the text will be here" size="36">
更新:
这是我尝试过但不起作用的方法: 这个显示一个空白字段:
<?php
//Path of file
$myFile = "test_file.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 ; ...)
echo $lines[$number_casual];
?>
<input name="accesspin" style="width: 300px" value="<?php echo htmlentities( $lines[$number_casual] ); ?>" size="36">
这个也显示一个空白字段:
<?php
//Path of file
$myFile = "test_file.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 ; ...)
echo $lines[$number_casual];
?>
<input name="accesspin" style="width: 300px" value="<?php echo $lines[$number_casual]; ?>" size="36">
这个让我的页面崩溃了:
<?php
//Path of file
$myFile = "test_file.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 ; ...)
echo '<input name="accesspin" style="width: 300px" value="' . htmlentities( $lines[$number_casual] ) . '" size="36">
?>
<input name="accesspin" style="width: 300px" value="<?php echo $lines[$number_casual]; ?>" size="36">
我的 .txt 文件不包含任何特殊字符。它看起来像这样:
text1
text2
text3
更新 2: 对不起大家。我不小心在 php 代码中输入了错误的 .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">
【问题讨论】:
-
所以把
$lines放到value属性中