PHP读取CSV文件内容 并且插入到数据库中
2018-06-26 13:360
- <?php
-
- $con = mysql_connect("localhost","root","");
- if (!$con){
- die('Could not connect: ' . mysql_error());
- }
- mysql_select_db("test", $con);
-
- function getCSVdata($filename)
- {
- $row = 1;//第一行开始
- if(($handle = fopen($filename, "r")) !== false)
- {
- while(($dataSrc = fgetcsv($handle)) !== false)
- {
- $num = count($dataSrc);
- for ($c=0; $c < $num; $c++)//列 column
- {
- if($row === 1)//第一行作为字段
- {
- $dataName[] = $dataSrc[$c];//字段名称
- }
- else
- {
- foreach ($dataName as $k=>$v)
- {
- if($k == $c)//对应的字段
- {
- $data[$v] = $dataSrc[$c];
- }
- }
- }
- }
- if(!empty($data))
- {
- $dataRtn[] = $data;
- unset($data);
- }
- $row++;
- }
- fclose($handle);
- return $dataRtn;
- }
- }
-
- $aData = getCSVdata('20141010SummaryOfData.csv');
- foreach($aData as $item){
-
- //插入到数据库
- }
- mysql_close($con);
- ?>