mysql批量导入txt文件
文章描述:
php读取txt文件批量导入
<?php
define('INIT_SYS', true);
require 'init.php';
header('Access-Control-Allow-Origin:*');
$ac = $_REQUEST['ac'];
if($ac=='admin_add') {
$result = r_txt();
$daytime = date("Y-m-d H:i:s",time());
$newstime = time();
foreach ($result as $k =>
$v) {
$v = str_replace("'","",$v);
$id = $db->
query("INSERT INTO " . $sys->
table('keys') . " (content,newstime,daytime) VALUE ('$v','$newstime','$daytime')");
}
}
if($ac=='admin_read') {
$db->
get_results("SELECT * FROM ".$sys->
table('keys')."");
$db->
debug();
}
$items = $db->
get_results("SELECT id FROM ".$sys->
table('keys')."",ARRAY_A);
//print_r($items);
$str_rand = array_rand($items,3);
//print_r($str_rand);
$files = array();
foreach ($items as $k=>
$v) {
if(in_array($k, $str_rand)) {
$files[] = $v;
}
}
//print_r($files);
//查询随机三条
$ids = arr_to_str($files);
$result = $db->
get_results("SELECT content FROM ".$sys->
table('keys')." WHERE id in($ids)",ARRAY_A);
//print_r($result);
//数组拼装字符
foreach($result as $key=>
$vals) {
$datastr.=$vals['content'].',';
}
//echo $datastr;exit;
$data = array('content'=>
$datastr);
echo $json = json_encode($data);
function arr_to_str($arr) {
$t ='' ;
foreach ($arr as $v) {
$v = join(",",$v);
// 可以用implode将一维数组转换为用逗号连接的字符串,join是别名
$temp[] = $v;
}
foreach ($temp as $v) {
$t.="'".$v."',";
}
$t = substr($t, 0, -1);
// 利用字符串截取函数消除最后一个逗号
return $t;
}
//读取文件
function r_txt() {
//取得当前文件所在目录
$dir = dirname(dirname(__FILE__));
//判断目标目录是否是文件夹
$file_arr = array();
if(is_dir($dir)) {
//打开
if($dh = @opendir($dir)) {
//读取
while(($file = readdir($dh)) !== false) {
if($file != '.' &
&
$file != '..') {
$file_arr[] = $file;
}
}
//关闭
closedir($dh);
}
}
//获取txt所有文件
$file_str = array();
foreach ($file_arr as $key=>
$val) {
if(substr($val,-4)=='.txt') {
$file_str[] = $val;
}
}
//print_r($file_str);
$result = [];
foreach ($file_str as $k =>
$v) {
$number = $k + 1;
//$key = "第 $number 个文件的内容";
$key = $number;
$f = fopen($dir."\".$v, 'r');
$content = fread($f, filesize($dir."\".$v));
fclose($f);
$result[$key] = $content;
}
return $result;
}
发布时间:2022/01/07
发表评论