2021-02-04

PHP 读取cvs文件,并写入到mysql

示例代码

/**
 * 数据库语句
 CREATE TABLE `cvs_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`field1` varchar(32) DEFAULT '',
`field2` varchar(32) DEFAULT '',
`field3` varchar(32) DEFAULT '',
`field4` varchar(32) DEFAULT '',
`field5` varchar(32) DEFAULT '',
`field6` varchar(32) DEFAULT '',
`field7` varchar(32) DEFAULT '',
`field8` varchar(32) DEFAULT '',
`field9` varchar(32) DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 */
$file = fopen('20210204.csv', 'r');
$i = 0;
while($data = fgetcsv($file)) {
    dataIconv($data);
    $arr[] = $data;
}

function dataIconv(&$data){
    foreach ($data as $key => $value) {
        $data[$key] = iconv('gb2312', 'utf-8', $value);
    }
}
//var_dump($arr);
$j = 0;
foreach ($arr as $value){
    //var_dump($value);
    $k = 0;
    foreach ($value as $item) {
        if ($k < 9) {
            $ind = 'field' . ($k + 1);
            $insertData[$j][$ind] = $item;
            $k++;
        }
    }
    $j++;
}
var_dump($insertData);
/*foreach ($insertData as $datum) {
    //TODO 一行一行的insert就好了
}*/

发表回复

Your email address will not be published. Required fields are marked *