我有这个php代码来读取文本文件,并生成一个html表,但我不想在代码中包含文件名,这个文件名应该来自尚未上传的文本文件,你能给出解决方案吗?
<?php
$filepath = 'files/the_file.txt';
if (file_exists($filepath)) {
$file = fopen($filepath, 'r');
echo '<table border=1>';
while (!feof($file)) {
$line = fgets($file);
$first_char = $line[0];
if ($first_char != '*' && $first_char != '^' && trim($line) != '') {
if (strstr($line, '|')) {
$split = explode('|', $line);
echo '<tr>';
foreach($split as $line) {
echo '<td>'.$line.'</td>';
}
echo '</tr>';
} else {
echo '<tr><td>'.$line.'</td></tr>';
}
}
}
echo '</table>';
} else {
echo 'the file does not exist';
}
?>
我不想事先指定文件路径,应该在文件上传到 HTML 页面后读取,如下所示,
<html>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br />
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
但是同样还有上传文件的代码,upload_file.php,
<?php
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
} else {
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
}
?>
只需将您的表单发布到带有表单生成的 php 文件,并将他汀类药物$filepath替换为 $filepath = $_FILES["file"]["tmp_name"];
upload_file.php
<?php
if (isset($_FILES[file])
&& $_FILES["file"]["error"] == UPLOAD_ERR_OK
&& file_exists($_FILES["file"]["tmp_name"])) {
$filepath = $_FILES["file"]["tmp_name"];
$file = fopen($filepath, 'r');
echo '<table border=1>';
while (!feof($file)) {
$line = fgets($file);
$first_char = $line[0];
if ($first_char != '*' && $first_char != '^' && trim($line) != '') {
if (strstr($line, '|')) {
$split = explode('|', $line);
echo '<tr>';
foreach($split as $line) {
echo '<td>'.$line.'</td>';
}
echo '</tr>';
} else {
echo '<tr><td>'.$line.'</td></tr>';
}
}
}
echo '</table>';
} else {
echo 'the file does not exist';
}
您拥有所需的所有代码。 :)您只需要将主表生成代码包装在 if 语句中,该语句将检查上传的文件是否正确:
if($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
if (file_exists($_FILES["file"]["tmp_name"])) {
$file = fopen($_FILES["file"]["tmp_name"], 'r');
// Rest of CODE to generate your table
}
请注意,如果您不使用 move_uploaded_file() 移动您上传的文件,它最终将被删除。