2015-05-29 132 views
1

這是我的問題,我正在嘗試爲每個新的txt文件創建一個在數據庫中創建新表的腳本。這部分是確定的,但我想在txt文件中獲取一些特定的行或單詞來更新表。如何在PHP中獲取txt文件中的特定行?

這裏是我的代碼:

<?php 

    $servername = "localhost"; 
    $username = "root";   
    $password = "";    
    $dbname = "exctraction";   

    $conn = new mysqli($servername, $username, $password, $dbname); 

    if ($conn->connect_error) 
    { 
     die("Connection failed: " . $conn->connect_error);  
    } 



    foreach (glob("*.txt") as $filename) 
    { 

     $sql = "CREATE TABLE IF NOT EXISTS `$filename` (
       `id` int(100) unsigned NOT NULL AUTO_INCREMENT,   
       `device` varchar(30) NOT NULL, 
       `label` varchar(30) NOT NULL, 
          `configured` varchar(3) NOT NULL, 
       PRIMARY KEY (`id`) 
      ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;"; 


     if ($conn->query($sql) === TRUE) 
     { 
      echo "<b>La table ".$filename."&nbsp;"." a &eacute;t&eacute; cr&eacute;&eacute;e avec succ&egrave;s.</b> </br>"; 
     } 
     else 
     { 
      echo "<u>Erreur lors de la cr&eacute;ation de la table :</u> </br>" . $conn->error; 
     } 

       $file = fopen($filename, "r"); 
       $content = ""; 

       for($i = 0 ; $i < 158 ; $i++) 
       { 

        $content .= fgets($file, 200); 
        if($i==65) 
        { 
         $content_array = file($filename); 
         print_r ($content."</br>"); 
        } 

       } 
       fclose($file); 
     } 
     ?> 

我要顯示我需要的線,然後進行更新表,這些行。

我想要得到的行在txt文件中是從57到65,但我無法獲得這些行。

+0

刪除「。」從'$ content。= fgets($ file,200);' – IshaS

+0

我試過了,沒有任何顯示。 – Maxime

回答

1
<?php 
$File = "file.txt"; // I assume your file has 57th and 65th line 
$fhandle = fopen($File, 'r'); 
while(!feof($fhandle)) // until end of file 
{ 
    $data[] = fgets($fhandle); // place each line to array 
    //Do whatever you want with the data in here 
    //This feeds the file into an array line by line 
} 
fclose($fhandle); 
echo "<pre>"; // makes output easier to read 
print_r($data[56].$data[64]); // outputs 57th and 65th line 

?> 
+0

要顯示58到65行,我該怎麼寫? – Maxime

+0

我的不好,很匆忙。增加了一些解釋。 – user3227275

+0

這不顯示從58到65的所有行,只是58和59,並且它們不完整。 – Maxime

相關問題