如何在php中上传和parsingCSV文件

我想用php上传一个csv文件。 file upload后,我想显示CSV文件的数据。 我想要一个例子如何完成这个任务。

虽然你可以很容易地find一个教程如何处理file upload与PHP,并有function(手动)来处理CSV,我会张贴一些代码,因为就在前几天我工作的项目,包括一些代码,你可以使用…

HTML:

 <table width="600"> <form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data"> <tr> <td width="20%">Select file</td> <td width="80%"><input type="file" name="file" id="file" /></td> </tr> <tr> <td>Submit</td> <td><input type="submit" name="submit" /></td> </tr> </form> </table> 

PHP:

 if ( isset($_POST["submit"]) ) { if ( isset($_FILES["file"])) { //if there was an error uploading the file if ($_FILES["file"]["error"] > 0) { echo "Return Code: " . $_FILES["file"]["error"] . "<br />"; } else { //Print file details echo "Upload: " . $_FILES["file"]["name"] . "<br />"; echo "Type: " . $_FILES["file"]["type"] . "<br />"; echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />"; echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />"; //if file already exists if (file_exists("upload/" . $_FILES["file"]["name"])) { echo $_FILES["file"]["name"] . " already exists. "; } else { //Store file in directory "upload" with the name of "uploaded_file.txt" $storagename = "uploaded_file.txt"; move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename); echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />"; } } } else { echo "No file selected <br />"; } } 

我知道必须有一个更简单的方法来做到这一点,但我读取CSV文件,并将每个logging的单个单元存储在一个二维数组中。

 if ( $file = fopen( "upload/" . $storagename , r ) ) { echo "File opened.<br />"; $firstline = fgets ($file, 4096 ); //Gets the number of fields, in CSV-files the names of the fields are mostly given in the first line $num = strlen($firstline) - strlen(str_replace(";", "", $firstline)); //save the different fields of the firstline in an array called fields $fields = array(); $fields = explode( ";", $firstline, ($num+1) ); $line = array(); $i = 0; //CSV: one line is one record and the cells/fields are seperated by ";" //so $dsatz is an two dimensional array saving the records like this: $dsatz[number of record][number of cell] while ( $line[$i] = fgets ($file, 4096) ) { $dsatz[$i] = array(); $dsatz[$i] = explode( ";", $line[$i], ($num+1) ); $i++; } echo "<table>"; echo "<tr>"; for ( $k = 0; $k != ($num+1); $k++ ) { echo "<td>" . fields[$k] . "</td>"; } echo "</tr>"; foreach ($dsatz as $key => $number) { //new table row for every record echo "<tr>"; foreach ($number as $k => $content) { //new table cell for every field of the record echo "<td>" . $content . "</td>"; } } echo "</table>"; } 

所以我希望这会有所帮助,这只是一小段代码,我还没有testing过,因为我使用它稍有不同。 评论应该解释一切。

现在可以用更简单的方式来完成。

 $tmpName = $_FILES['csv']['tmp_name']; $csvAsArray = array_map('str_getcsv', file($tmpName)); 

这将返回一个CSV数据的parsing数组。 然后你可以使用foreach语句来循环。

未经testing,但应该给你的想法。 风景:

 <form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="csv" value="" /> <input type="submit" name="submit" value="Save" /></form> 

upload.php控制器:

 $csv = array(); // check there are no errors if($_FILES['csv']['error'] == 0){ $name = $_FILES['csv']['name']; $ext = strtolower(end(explode('.', $_FILES['csv']['name']))); $type = $_FILES['csv']['type']; $tmpName = $_FILES['csv']['tmp_name']; // check the file is a csv if($ext === 'csv'){ if(($handle = fopen($tmpName, 'r')) !== FALSE) { // necessary if a large csv file set_time_limit(0); $row = 0; while(($data = fgetcsv($handle, 1000, ',')) !== FALSE) { // number of fields in the csv $col_count = count($data); // get the values from the csv $csv[$row]['col1'] = $data[0]; $csv[$row]['col2'] = $data[1]; // inc the row $row++; } fclose($handle); } } } 

你需要PHP手册的处理file upload部分,你也可以看看fgetcsv()和explode()。

你可以试试这个:

 function doParseCSVFile($filesArray) { if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { $strFilePath = $filesArray['frmUpload']['tmp_name']; $strFileHandle = fopen($strFilePath,"r"); $line_of_text = fgetcsv($strFileHandle,1024,",","'"); $line_of_text = fgetcsv($strFileHandle,1024,",","'"); do { if ($line_of_text[0]) { $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')"; ExecuteQry($strInsertSql); } } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE); } else { return FALSE; } } 

嗨,我感觉str_getcsv – parsing一个CSVstring到数组是一个最好的select。 1.您需要将file upload到服务器2.使用str_getcsvparsing文件。 3.通过arrays,并根据你的需要在你的网站alignment。

 function doParseCSVFile($filesArray) { if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { $strFilePath = $filesArray['frmUpload']['tmp_name']; $strFileHandle = fopen($strFilePath,"r"); $line_of_text = fgetcsv($strFileHandle,1024,",","'"); $line_of_text = fgetcsv($strFileHandle,1024,",","'"); do { if ($line_of_text[0]) { $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')"; ExecuteQry($strInsertSql); } } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE); } else { return FALSE; } }