php读取TXT文件后写入数据库
例文本内容为53421312345,124,312453421312314,241,24125342131234,5432,342353421312323,434,324...
例文本内容为
534213123 45,124,3124
534213123 14,241,2412
534213123 4,5432,3423
534213123 23,434,3242
一行一行写入数据库。将前后分别写入两个字段 展开
534213123 45,124,3124
534213123 14,241,2412
534213123 4,5432,3423
534213123 23,434,3242
一行一行写入数据库。将前后分别写入两个字段 展开
1个回答
展开全部
<?php
$file_dir="1.txt";
$fp=fopen($file_dir,"r");
$content=fread($fp,filesize($file_dir));//读文件
fclose($fp);
function replaces($str)//为各字段添加''
{
foreach($str as $k=>$v)
{
$str[$k]="'".trim($v)."'";
}
return $str;
}
function Get_item($tmp1,$tmp2,$cont,$sq)//取得sql语句;tmp1为记录分割点,tmp2为字段分割点
{
$tmp_rows=explode($tmp1,$cont);
foreach($tmp_rows as $key=>$value)
{
$tmp_rows2[$key]=replaces(explode($tmp2,trim($value)));
$sql[$key]=$sq.implode(",",$tmp_rows2[$key]).")\"";
}
return $sql;
}
$sq="\"insert into table1 (a1,a2,a3) values (";//sql的前半部分,要完善!
$sql=array();
$sql=Get_item("-"," ",$content,$sq);
//$db=mysql_connect("localhost","root","abc");//联接mysql,自己加
//mysql_select_db(....
foreach($sql as $v)
{
mysql_query($v);//执行sql;
}
//mysql_close($db);
?>
或者生成一个1.sql文件,再把它导入mysql;
$file_dir="1.txt";
$fp=fopen($file_dir,"r");
$content=fread($fp,filesize($file_dir));//读文件
fclose($fp);
function replaces($str)//为各字段添加''
{
foreach($str as $k=>$v)
{
$str[$k]="'".trim($v)."'";
}
return $str;
}
function Get_item($tmp1,$tmp2,$cont,$sq)//取得sql语句;tmp1为记录分割点,tmp2为字段分割点
{
$tmp_rows=explode($tmp1,$cont);
foreach($tmp_rows as $key=>$value)
{
$tmp_rows2[$key]=replaces(explode($tmp2,trim($value)));
$sql[$key]=$sq.implode(",",$tmp_rows2[$key]).")\"";
}
return $sql;
}
$sq="\"insert into table1 (a1,a2,a3) values (";//sql的前半部分,要完善!
$sql=array();
$sql=Get_item("-"," ",$content,$sq);
//$db=mysql_connect("localhost","root","abc");//联接mysql,自己加
//mysql_select_db(....
foreach($sql as $v)
{
mysql_query($v);//执行sql;
}
//mysql_close($db);
?>
或者生成一个1.sql文件,再把它导入mysql;
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询