编写PHP页面实现一个CSV文件的上传;上传后对CSV进行解析,并以HTML的方式对CSV文件进行展示。另外,文件上传并显示成功后可以按照某个列(用户可选择)的升序或者降序(用户可选择)来生成HTML的显示页面。
时间: 2023-06-27 09:06:54 浏览: 190
以下是一个简单的实现步骤:
1. 创建一个HTML表单,包含一个文件上传的input和两个下拉框选择列和排序方式:
```html
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csvfile">
<select name="sortcol">
<option value="0">第一列</option>
<option value="1">第二列</option>
<option value="2">第三列</option>
</select>
<select name="sortorder">
<option value="asc">升序</option>
<option value="desc">降序</option>
</select>
<input type="submit" value="上传">
</form>
```
2. 创建一个PHP脚本upload.php,处理文件上传并解析CSV文件:
```php
<?php
if ($_FILES["csvfile"]["error"] == UPLOAD_ERR_OK) {
$filename = $_FILES["csvfile"]["tmp_name"];
$data = array();
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[] = $row;
}
fclose($handle);
}
// TODO: 排序并展示CSV数据
}
?>
```
3. 在TODO处添加排序逻辑,根据用户选择的列和排序方式对数据进行排序:
```php
$sortcol = $_POST["sortcol"];
$sortorder = $_POST["sortorder"];
usort($data, function ($a, $b) use ($sortcol, $sortorder) {
if ($sortorder == "asc") {
return $a[$sortcol] <=> $b[$sortcol];
} else {
return $b[$sortcol] <=> $a[$sortcol];
}
});
```
4. 在排序后展示CSV数据,生成HTML表格:
```php
echo "<table>";
foreach ($data as $row) {
echo "<tr>";
foreach ($row as $cell) {
echo "<td>$cell</td>";
}
echo "</tr>";
}
echo "</table>";
```
完整的代码如下:
```html
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csvfile">
<select name="sortcol">
<option value="0">第一列</option>
<option value="1">第二列</option>
<option value="2">第三列</option>
</select>
<select name="sortorder">
<option value="asc">升序</option>
<option value="desc">降序</option>
</select>
<input type="submit" value="上传">
</form>
```
```php
<?php
if ($_FILES["csvfile"]["error"] == UPLOAD_ERR_OK) {
$filename = $_FILES["csvfile"]["tmp_name"];
$data = array();
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[] = $row;
}
fclose($handle);
}
$sortcol = $_POST["sortcol"];
$sortorder = $_POST["sortorder"];
usort($data, function ($a, $b) use ($sortcol, $sortorder) {
if ($sortorder == "asc") {
return $a[$sortcol] <=> $b[$sortcol];
} else {
return $b[$sortcol] <=> $a[$sortcol];
}
});
echo "<table>";
foreach ($data as $row) {
echo "<tr>";
foreach ($row as $cell) {
echo "<td>$cell</td>";
}
echo "</tr>";
}
echo "</table>";
}
?>
```
阅读全文