将数据从数据库放到文本文件中

时间:2014-06-23 22:47:32

标签: php mysqli

我有一个包含例如的文本文件:

The Fulton County Grand Jury said Friday an investigation.
The jury further said in term-end presentments that the City Executive Committee.
etc..

我在数据库中有一个单词词典表,例如:

==========================
= id =    word  =  type  =
==========================
= 1  =  country = nn-tl  =
= etc...                 =
==========================

我必须在数据库中的字典上搜索我的文本文件的相同单词并获取相同单词的类型,然后将其类型添加到格式为words/type的文本文件中,因此最终结果必须是:

The/at Fulton/np-tl County/nn-tl Grand/jj-tl Jury/nn-tl said/vbd Friday/nr an/at investigation/nn ./.
etc..

这里是代码: connection.php

$db = new mysqli("localhost","root","root","peri");
if(mysqli_connect_errno()){
   trigger_error('Connection failed: '.$db->error);
}

主程序:

require_once 'connection.php';
$file  = "C:/AppServ/www/dictionary/text.txt";
$lines = file($file);
foreach($lines as $line_num => $line) {
     $parse = explode(' ', $line);  
     $query = $db->query("SELECT typeword FROM dictionary WHERE words = $parse");
     $result = $query->fetch_object();
      echo $parse '/' $result";
}

但它给了我错误消息Call to a member function fetch_object() on a non-object 请帮助我,谢谢你:)。

1 个答案:

答案 0 :(得分:0)

假设你有字典的字典表:id,word,type和你的示例文本文件,这可能是解决方案(也许你需要进行一些调整!):

$file  = "text.txt";



$lines = file($file);
foreach($lines as  $line) {
     $parse = explode(' ', $line);
     foreach ($parse as $word) {  

     //replace dot in last word in line
     $word_fix=str_replace('.','',$word);

     $query ="SELECT type FROM dictionary WHERE word = '$word_fix'";
     $result = $db->query($query);
   if($res = $result->fetch_object()) {

       echo $word.'/'.$res->type.' ';
   }

   else {
         echo $word.' /'.' ';
   }
     }
}

P.S。可能你必须替换:,!?...来匹配数据库中的单词...