简单实现读取txt文件数据并插入到数据库

      发布在:后端技术      评论:0 条评论
<?php

header('content-type:text/html;charset=utf-8');
require 'Medoo.php';

try{
$dbs = new \Medoo\Medoo([
// required
//    $conn = mysqli_connect($db_host, $db_user, $db_pwd);
       'database_type' => 'mysql',
'database_name' => 'tbneme',
'server' => '127.0.0.1',
'username' => 'root',
'password' => 'root',
// [optional]
       'charset' => 'utf8mb4',
'collation' => 'utf8_general_ci',
'port' => 3306,

// [optional] Table prefix
       'prefix' => '',

// [optional] Enable logging (Logging is disabled by default for better performance)
       'logging' => true,

// [optional] MySQL socket (shouldn't be used with server and port)
//    'socket' => '/tmp/mysql.sock',

       // [optional] driver_option for connection, read more from http://www.php.net/manual/en/pdo.setattribute.php
       'option' => [
PDO::ATTR_CASE => PDO::CASE_NATURAL
       ],

// [optional] Medoo will execute those commands after connected to the database for initialization
       'command' => [
'SET SQL_MODE=ANSI_QUOTES'
       ]
]);
$filePath = 'sj.txt';
//file_get_contents() 函数把整个文件读入一个字符串中。

   $contents = file_get_contents($filePath);
//获取文件的编码方式
   $encoding = mb_detect_encoding($contents, array('GB2312','GBK','UTF-8','ASCII'));
$file = fopen($filePath, "r"); // 以只读的方式打开文件
   if(empty($file)){
$errorCode = 201;
$errorMessage = "file not found";
return;
}
$i = 0;
//输出文本中所有的行,直到文件结束为止。
   while(!feof($file)) {
$itemStr = fgets($file); //fgets()函数从文件指针中读取一行

       if ($encoding !== false) {

//iconv ()$encoding 转换成“UTF-8”
           $itemStr = iconv($encoding, 'UTF-8', $itemStr);

} else {
$itemStr = mb_convert_encoding ($itemStr, 'UTF-8','Unicode');

}
$itemStr=trim($itemStr);
preg_match('#¥(\d+\.\d+)$#',$itemStr,$match);

//        $itemArray=preg_split("/\s+/",$itemStr);

      $goods_price='0.00';
if(isset($match[1])){
$goods_price=$match[1];
}
$goods_name=preg_replace('#¥(\d+\.\d+)$#','',$itemStr);
$goods_name=trim($goods_name);
//存在看是否注册
       $info=$dbs->get("xy_goods_list",'*', [
'goods_name'=>$goods_name
]);
if(!$info){
//            不存在则插入 `status`, `cid` shop_name`, `goods_name`, `goods_info`, `goods_price`, `goods_pic`, `addtime`, `status`, `cid`
           $dbs->insert("xy_goods_list", [
'shop_name'=>'淘商宝','goods_name'=>$goods_name,'goods_price'=>$goods_price,'addtime'=>time(),'goods_pic'=>'/static/image/timg.jpg',
'status'=>0,
'cid'=>1,
]);
var_dump($i.'插入成功');
}else{
var_dump($info,'存在不插入');
}

var_dump($goods_name);
++$i;
}
var_dump($i);
}catch (Exception $exception){
$errorCode = $exception->getCode();
$errorMessage = $exception->getMessage();
}


相关文章
热门推荐