php上传csv文件,然后导入到数据库中。
代码:
<?php
$_LANG['express_list']['type'] = '快递类型';
$_LANG['express_list']['order_sn'] = '订单号';
$_LANG['express_list']['province'] = '快递省份';
$_LANG['express_list']['weight'] = '重量';
$_LANG['express_list']['price'] = '价格';
$filesname = $_FILES['file']['name'];
$attach_ext = strtolower(substr(strrchr($filesname,'.'),1));
if($attach_ext == 'csv' )
{
/* 将文件按行读入数组,逐行进行解析 */
$line_number = 0;
$goods_list = array();
$field_list = array_keys($_LANG['express_list']); // 字段列表
$data = file($_FILES['file']['tmp_name']);
foreach ($data AS $line)
{
// 跳过第一行
if ($line_number == 0)
{
$line_number++;
continue;
}
// 转换编码
$line = ecs_iconv('GB2312', 'UTF8', $line);
// 初始化
$arr = array();
$buff = '';
$quote = 0;
$len = strlen($line);
for ($i = 0; $i < $len; $i++)
{
$char = $line[$i];
if ('' == $char)
{
$i++;
$char = $line[$i];
switch ($char)
{
case '"':
$buff .= '"';
break;
case ''':
$buff .= ''';
break;
case ',';
$buff .= ',';
break;
default:
$buff .= '' . $char;
break;
}
}
elseif ('"' == $char)
{
if (0 == $quote)
{
$quote++;
}
else
{
$quote = 0;
}
}
elseif (',' == $char)
{
if (0 == $quote)
{
if (!isset($field_list[count($arr)]))
{
continue;
}
$field_name = $field_list[count($arr)];
$arr[$field_name] = trim($buff);
$buff = '';
$quote = 0;
}
else
{
$buff .= $char;
}
}
else
{
$buff .= $char;
}
if ($i == $len - 1)
{
if (!isset($field_list[count($arr)]))
{
continue;
}
$field_name = $field_list[count($arr)];
$arr[$field_name] = trim($buff);
}
}
$express_list[] = $arr;
}
// 根据导入数据格式 插入数据库中
if(!empty($express_list))
{
// 清空数据库
$sql = "TRUNCATE TABLE ecs_express_compare_tmp";
$res = $GLOBALS['db']->query($sql);
foreach($express_list as $val)
{
$sql = "INSERT INTO express_compare_tmp (type,order_sn,province,weight,price) ".
" VALUES('$val[type]','$val[order_sn]','$val[province]','$val[weight]','$val[price]')";
$res = $GLOBALS['db']->query($sql);
}
// 提示成功
}
else
{
// 提示错误
}
}
else
{
// 提示错误
}