我是一個帶AJAX的新手,我問是否可以從「文件輸入」中讀取CSV文件,並從中提取數據並顯示數據沒有掩飾形式的同一頁面。 這裏是我的代碼:Ajax - PHP:從CSV文件中提取數據而不提交
的index.html:
<!DOCTYPE html>
<html>
<head>
<title>Choose a CSV File</title>
</head>
<body>
<h1>Choose a CSV file :</h1>
<form method="post" action="csv_to_array.php" enctype="multipart/form-data">
<div>
<input type="file" name="file" required/>
<input type="submit" value="Upload CSV Data" />
</div>
</form>
<div>
<!-- diplaying the data extracted from the csv file -->
</div>
</body>
</html>
csv_to_array.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"]. "<br>";
$users = array();
$labels = array('id', 'name', 'age');
$fh = fopen ($_FILES["file"]["tmp_name"], 'r');
fgetcsv($fh);
if ($fh) {
while (!feof($fh)) {
$row = fgetcsv($fh, 500, ';');
$tempRow = array();
if (isset($row) && is_array($row) && count($row)>0) {
foreach ($row as $key => $value) {
$tempRow[$labels[$key ]] = $value;
}
$users[] = $tempRow;
}
}
fclose($fh);
$numLines = count($users);
}
// I want this to be displayed in index.html :
echo $numLines;
echo '<table style="border: 1px solid black;">';
echo '<tr>';
echo '<td>ID</td>';
echo '<td>NAME</td>';
echo '<td>AGE</td>';
echo '</tr>';
for ($x=0; $x<$numLines; $x++) {
echo '<tr>';
echo '<td>'.$users[$x]['id'].'</td>';
echo '<td>'.$users[$x]['name'].'</td>';
echo '<td>'.$users[$x]['age'].'</td>';
echo '</tr>';
}
echo '</table>';
}
?>
預先感謝您的傢伙!
參見:http://stackoverflow.com/a/8244082/1981678 – briansol 2014-09-02 18:10:32