今天分享些php导入文件读取数据插入数据到数据库的代码,涉及的场景如下:
- 数据库表系统数据(如:省市区)
- 前端页面从文件导入数据,插入数据库(如:黑名单导入)
第一个是一个php的脚本代码,实现思路是读取txt文件内容,生成插入sql的语句,然后执行sql,完成。
要导入的数据
代码实现
代码简单介绍一下,本脚本是在自行封装的带有swoole扩展的php框架,request是已经封装好的函数用于接收的参数(类似$_GET[]);fopen读取对应路径的文件(路径可修改)(txt文件一行一个城市名称),循环读取每一行并按照格式赋值到一数组中;执行foreach循环,生成sql语句;应用mysql连接池,执行sql,插入数据(可用原生mysql执行函数);log日志打印结果;respose返回数据查看,完!
<?php
public function importData()
{
$request = $this->request()->getRawParams();
$table = $request['table'];
$fileName = $request['file_name'];
$fileNum = $request['file_num'];
$remark = $request['remark'];
$return_sql = [];
$return_success = [];
for ($i = 0; $i < $fileNum; $i++) {
$filename = ROOT_PATH . '/bootstrap/'.$fileName.'/'.$i.'.txt';
$fps=fopen($filename,'r');
$temp = [];
while(!feof($fps)){
$ceshi=fgets($fps);
$temp[] = [
'keyq' => 'area',
'key_name' => '城市等级,
'codeq' => $i,
'code_name' => str_replace("\r\n","",$ceshi),
'remark' => is_array($remark)?$remark[$i]:$remark,
];
}
$filter = '';
$key_list = '';
foreach ($temp as $value) {
$key_list = implode(",", array_keys($value)) . "";
$value_list = "'" . implode("','", array_values($value)) . "'";
$filter .= "(" . $value_list . "),";
}
$sql = "insert" . " into " . $table . "(".$key_list.") values ".$filter;
$sql = substr($sql,0,strlen($sql)-1).';';
$conn = MysqlPool::getInstance()->getObj(60);
$result = $conn->insertQuery($sql);
MysqlPool::getInstance()->recycleObj($conn);
Log::getInstance()->info($result);
$return_sql[] = $sql;
$return_success[$i] = $result??0;
}
$this->response()->setResult( Result::success($return_sql));
}
第二个是更深一层的封装读取文件,并插入到数据库
要导入数据
黑名单导入
函数参数介绍:
- $filePath 文件的tmp_name
- $startRow 开始读取的行数,默认0行
- $checkTitle 是否检查标题,默认false
- $titkeRaw 文件标题在第几行,默认0行
- $titleConfig 标题格式(数组),例如:array('黑名单'=>'word');
- $keys 内容格式(数组)例如:array('word');
代码实现
public function readCsv($filePath, $startRow = 0, $checkTitle = false, $titleRow = 0, $titleConfig = [], $keys = [])
{
$row = (is_numeric($startRow) && $startRow >= 0) ? $startRow : 0;
$titleIndexArr = array();
$resultArr = array();
$wordsArray = [];
$file = fopen($filePath, 'r');
//读取文件内容
while ($data = fgetcsv($file)) {
$rowCount = count($data);
if ($rowCount > 0) {
for ($r = 0; $r < $rowCount; $r++) {
$data[$r] = mb_convert_encoding($data[$r], 'UTF-8', 'GBK,GB2312,UTF-8');
}
$wordsArray[] = $data;
}
}
fclose($file);
$rowCount = count($wordsArray);
for (; $row < $rowCount; $row++) {
$tempArr = $wordsArray[$row];
if (isset($tempArr) && !empty($tempArr)) {
$dataArr = array();
///验证标题行
if ($checkTitle && $row == $titleRow) {
foreach ($tempArr as $key => $value) {
$dataArr[$key] = trim(str_replace("'", '', str_replace("\"", '', $value)));
}
$titleIndexArr = $this->checkTitle($dataArr, $titleConfig, $keys);
if (empty($titleIndexArr)) {
return array('code' => 1, 'msg' => '导入文件格式内容有误,请检查导入文档是否正确');
}
} else {
if ($checkTitle && !empty($titleIndexArr)) {
foreach ($tempArr as $key => $value) {
if (!isset($titleIndexArr[$key]) || empty($titleIndexArr[$key])) {
continue;
}
$keyStr = $titleIndexArr[$key];
$dataArr[$keyStr] = trim(str_replace("'", '', str_replace("\"", '', ltrim($value, '=\"'))));
}
} else {
foreach ($tempArr as $key => $value) {
$dataArr[] = trim(str_replace("'", '', str_replace("\"", '', ltrim($value, '=\"'))));
}
}
$resultArr[$row] = $dataArr;
}
}
}
return array('code' => 0, 'msg' => 'success', 'datas' => $resultArr);
}
/**
* 验证标题行并返回各属性对应的index
* @param $titleArr
* 表头配置 格式:array(key=>value); key:表头名,value:要替换成的code 例:array('订单编号'=>'order_sn')
* @param $titleConfig
* 表头必须要有的key数组, 例: array('order_sn', 'order_status')
* @param $keys
* @return array
*/
protected function checkTitle(array $titleArr, array $titleConfig, array $keys = array())
{
///根据标题行,排列数据
if (empty($titleArr) || empty($titleConfig)) {
return array();
}
$resultArr = array();
foreach ($titleArr as $key => $value) {
$resultArr[$key] = isset($titleConfig[$value]) ? $titleConfig[$value] : '';
}
if (!empty($keys)) {
foreach ($keys as $mk => $mv) {
$flag = array_search($mv, $resultArr);
if ($flag === false) {
return array();
}
}
}
return $resultArr;
}