我有这个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"];
}
?>
答案 0 :(得分:0)
您拥有所需的所有代码。 :) 您只需要将主表生成代码包装在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()移动上传的文件,则最终会被删除。
答案 1 :(得分:0)
只需将表单发布到带有表单生成的php文件,并将statin $ 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';
}