PHP将txt文本词库导入数据库中

<?php
/**
 * Created by PhpStorm.
 * User: zhangq
 * Date: 2018/5/18
 * Time: 9:09
 */


header("Content-type: text/html; charset=utf-8");
set_time_limit(0);
$conn = mysql_connect('数据库ip','账号','密码') or die("Invalid query: " . mysql_error());
mysql_select_db('pingcha', $conn) or die("Invalid query: " . mysql_error());
echo "数据库连接完成";//数据库连接
$txtd='/mnt/zhangq/data/';//服务器地址
$f = scandir($txtd);//读取地址下文件
foreach($f as $file) {
//    $txt= iconv('gbk', 'utf-8', $file);转码
    $txt= str_replace(".txt", "", $file);
    $content = file_get_contents($txtd.$file);
//    $content=iconv("gbk", "utf-8",$content);windos与linux系统编码不同 window下需要加上
    //echo $content;
    $contents = explode(PHP_EOL, $content);//explode()函数以换行为标识符进行拆分

    foreach ($contents as $k)//遍历循环
    {
        $word = $k;

        //echo $txt;
//数据库插入操作
        mysql_query("insert into pc_dictionary (`word`,`type`)
      VALUES('$word','$txt')");

    }
    echo $txt."插入完成<br>";
}

1.了解了php与数据库的连接。

$conn = mysql_connect('数据库ip','账号','密码') or die("Invalid query: " . mysql_error());
mysql_select_db('pingcha', $conn) or die("Invalid query: " . mysql_error());
mysql_query("insert into pc_dictionary (`word`,`type`)
      VALUES('$word','$txt')");

2.了解了在linux下在服务器上跑程序。

猜你喜欢

转载自blog.csdn.net/sinat_40297086/article/details/80374210