PHP逐行解析文件,并写入数据库


$filePath为文件路径,上传文件则返回文件路径调用下面函数即可
public function readText($filePath,&$errorCode,&$errorMessage)
{
try{
$file = fopen($filePath, "r"); // 只读文件
if(empty($file)){
$errorCode = 201;
$errorMessage = "file not found";
return;
}
$i = 1;
//输出文本中所有的行,直到文件结束为止。
while(!feof($file)) {
$itemStr = fgets($file); //fgets()函数从文件指针中读取一行
$itemArray = explode(" ",$itemStr); // 将tab分割的各部分内容提取出来
$itemArray = array_filter($itemArray); // 对itemArray进行校验

       //$itemArray为每一行的解析数据,自行打印写入数据库即可,也可根据打印结果转换成数组
//自己的代码

++$i;
}
fclose($file);
}catch (Exception $exception){
$errorCode = $exception->getCode();
$errorMessage = $exception->getMessage();
}
return true;
}

原文链接:https://www.cnblogs.com/mydesky2012/p/7121577.html(感谢博主分享)
原文地址:https://www.cnblogs.com/luqiang213917/p/9414345.html