php上传csv,如何在php中上传和解析CSV文件

小编典典

尽管您可以轻松找到如何使用php处理文件上传的教程,并且有一些功能(手动)可以处理CSV,但是我将发布一些代码,因为几天前我从事一个项目,其中包括一些代码,您可以采用…

HTML:

Select file
Submit

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"] . "
";

}

else {

//Print file details

echo "Upload: " . $_FILES["file"]["name"] . "
";

echo "Type: " . $_FILES["file"]["type"] . "
";

echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb
";

echo "Temp file: " . $_FILES["file"]["tmp_name"] . "
";

//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"] . "
";

}

}

} else {

echo "No file selected
";

}

}

我知道必须有一种更简单的方法来执行此操作,但是我读取了CSV文件并将每个记录的单个单元格存储在二维数组中。

if ( isset($storagename) && $file = fopen( "upload/" . $storagename , r ) ) {

echo "File opened.
";

$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 "

echo "

";

for ( $k = 0; $k != ($num+1); $k++ ) {

echo "

" . $fields[$k] . "";

}

echo "

";

foreach ($dsatz as $key => $number) {

//new table row for every record

echo "

";

foreach ($number as $k => $content) {

//new table cell for every field of the record

echo "

" . $content . "";

}

}

echo "

";

}

因此,我希望这会有所帮助,这只是一小段代码,并且我尚未对其进行测试,因为我使用的代码略有不同。评论应解释一切。

2020-05-26

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值