php逐行读取文件源代码如下:

<html>
<head>
< >php实例之按行读取文件内容</ >
</head>
<body>
<?php
$filename = \"test.txt\";
$fp = fopen( $filename, \"r\" ) or die(\"Couldn\'t open $filename\");
while ( ! feof( $fp ) ) {
   $line = fgets( $fp, 1024 );
   print \"$line<br>\";
}
?>
</body>
</html>

 

在看下面是个实例,该实例逐行读取文件中的数据并使用正则表达式处理每一行的数据,然后进行数据库操作。

$handle = @fopen(\"D:/public/test.txt\", \"r\");
if ($handle) {
    while (!feof($handle)) {
    
        $str = fgets($handle, 4096);
       
  //$str = \'#主单词1#\';
  if(preg_match(\'/#(.+)#/\',$str,$matches)){
     
     $di_word = $matches[1];
     $di_word = mysql_escape_string($di_word);
     $sql = \" SELECT di_id FROM `du_index` WHERE di_word = \'{$di_word}\'\";
     $result = mysql_query($sql);
     $row = mysql_fetch_row($result);
     $di_id =  $row[0];
     if (count($dy_word)>0){
      $sql = \" INSERT INTO `du_yun` (`di_id`,`di_word`,`dy_word`,`dy_de ion`,`dy_status`,`dy_time`) VALUES\";
      for ($i=0;$i<count($dy_word);$i++){
     $sql .= \" (\'{$di_id_1}\',\'{$di_word_1}\',\'{$dy_word[$i]}\',\'{$dy_de ion[$i]}\',\'1\',now()),\";
     
      }
      $result = mysql_query(substr($sql,0,-1).\';\');
      if ($result){}else{
      echo $sql . \'<br />\';
         }
     }
     $di_id_1 = $di_id;
     $di_word_1 = $di_word;
     $dy_word = $dy_de ion = array();
     $sql = \'\';
     continue;
  }; 
  //$str = \'[志願者]參[與]人員\';
  /* http://www.manongjc.com/article/1384.html */
  if (preg_match(\'/^\\[(.+)\\](.+)$/\',$str,$matches)){
     $dy_word[]        = trim($matches[1]);
     $dy_de ion[] = trim($matches[2]);
     continue;
  }
  
 }
 if (count(dy_word)>0){
     $sql = \" INSERT INTO `du_yun` (`di_id`,`di_word`,`dy_word`,`dy_de ion`,`dy_status`,`dy_time`) VALUES\";
     for ($i=0;$i<count($dy_word);$i++){
       $sql .= \" (\'{$di_id_1}\',\'{$di_word_1}\',\'{$dy_word[$i]}\',\'{$dy_de ion[$i]}\',\'1\',now()),\";
       
     }
     $result = mysql_query(substr($sql,0,-1).\';\') or die(mysql_error());
        if ($result){}else{
      echo $sql . \'<br />\';
     }
 }
    fclose($handle);
}
收藏 打印