html
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="csv" value="" />
<input type="submit" name="submit" value="Save" /></form>
</form>
我需要帮助读取上传的csv文件中的值,并且使用 echo json_encode($csv) 将其输出为json格式。我尝试过获取这些值,但是一直都是null。
<?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);
while(($data = fgetcsv($handle, 10000, ',')) !== FALSE) {
// number of fields in the csv
$col_count = count($data);
// get the values from the csv
}
array_walk($csv, function(&$a) use ($csv) {
$a = array_combine($csv[0], $a);
});
array_shift($csv); # remove column header
header('Content-Type: application/json');
echo json_encode($csv); //display array
fclose($handle);
}
}
}
?>
示例CSV
LastName,FirstName,MAT251-Calc-I ,MAT252-Calc-II,MAT320-DiscreteMath,CPS210-CompSci-I,CPS310-CompSci-II,CPS315-CompSci-III,CPS352-OOP,CPS330-Assembly.Arch.,CPS353-SoftEng,CPS415-Disc.Cont.Algorithms,CPS340-Op.Sys,CPS425-Lang.Processing,CPS493-Elect-1,CPS493-Projects,EGC230-Dig.Logic,EGC208-Dig.Logic.Lab,SCIENCE-I,SCIENCE-II
Rocha, Cara I.,A,A,A,C-,,,,,,,,,,,,,,
Hamilton, Mufutau N.,B,B,B,A-,,,,,,,,,,,,,,
Castro, Chiquita A.,B,B,C ,C ,,,,,,,,,,,,,,
Juarez, Edward Y.,C+,B,B,C,A,C+,B,B,C,A,C+,B,B,C,A,C+,A,B
Erickson, Norman H.,C-,B-,C+,B,B,B,,C-,B,,,,,,,B,,
Downs, Moana C.,A,C+,B,C-,A,C-,,A-,B+,,,,,,,,,