php读取txt文件 然后写入数据库

2024-11-16 13:06:09
推荐回答(4个)
回答1:

$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;

回答2:

$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;

回答3:

给你举个很简单的例子,如下:






/*写入*/
if ($_POST[Submit]) {
$fp=fopen("db.txt","a");
fwrite($fp,$_POST[user]."|".$_POST[pass]."\r\n"); //写入数据,中间用|隔开
fclose($fp);
}
/*读取,可以通过|拆分项*/
$lines=file("db.txt");
print_r("
"); 
print_r($files);
/*删除*/
你可以用一项来做标识,比如提交时间,来定位行数。
?>

回答4:

privatePointUrl1,phone,lat,NId,transferTation,lon,privatePointId,address,publishStatus,briefDescription,keyword,mainInfotype,infotype,description,postCode,name,cityCode,privatePointUrl
,,0.0,MAPBHIHBJEFBXOSRXNCNX,,0.0,8695,规范化,0,,,,,,,东方更好发挥,010,
,,0.0,MAPBCIHBJEFBXOSRXNCIX,,0.0,8694,共和国和,0,,,,,,,可呵呵,010,
,,0.0,MAPBQIHBJEFBXOSRXNCWX,,0.0,8693,成功后,0,,,,,,,覆盖和法国,010,

文件形式如上,我如何读取其中的2个字段,比如说nid 和privatePointId 然后后根据数据库中的id与privatePointId 对应,写入nid到数据库中!