2016-05-06 56 views
-4

如何從txt文件讀取特定行數?例如,我有一個有100行的txt文件,我需要打印25或50行到我的網站?我搜索了網站,無法找到如何使用PHP或JavaScript做到這一點。謝謝!從文件讀取可變行數php

現在我有

<?php 
        if(isset($_GET['submit'])) 
        { 

         $pavadinimas = htmlentities($_GET['pavadinimas']); 



         $result = Myfunction($pavadinimas); 



         $string = file_get_contents("istorija.txt"); 
         $array = explode(PHP_EOL, $string); 

         function Myfunction($pavadinimas){ 

         For($i=0;$i<=$pavadinimas($array);$i++){ 
         echo $array[$i] ."<br>\n"; 
         } 
         } 
        } 
        ?> 

        <?php if(isset($result)) echo $result; //print the result above the form ?> 

        <form action="administratorius.php" method ="GET" > 
        Įrašų skaičius: 
        <input type="text" name="pavadinimas" maxlength="30" value="<?php echo $form->value("pavadinimas"); ?>"> <br> 

        <input type="submit" name="submit" value="Prideti"> 
        </form> 

我想,我的輸入將作爲函數的變量。我如何使它工作?謝謝!

+3

你能告訴我們你試過了什麼嗎? – DevDonkey

回答

1

您需要分解[return]上的字符串。

$string = file_get_contents("file.txt"); 
$array = explode(PHP_EOL, $string); 

編輯:EOL更好。已經忘記了。
EDIT2:

For($i=0;$i<=count($array);$i++){ 
    echo $array[$i] ."<br>\n"; 
} 

這上面的代碼將輸出的全部文本文件。
$i=0表示從第一行開始。
$i<=count($array)繼續直到文件結束。這可以更改爲$i<=15,並且只輸出15行。
$i++意味着當時只有一個。

然後有一個迴音輸出行號$i

編輯:我不知道你正在嘗試做的。但是,這是我最好的代碼的猜測:

if(isset($_GET['submit'])){ 
     $pavadinimas = htmlentities($_GET['pavadinimas']); 
     $result = Myfunction($pavadinimas, 25); //reads 25 rows of the pavadinimas 
     $string = file_get_contents("istorija.txt"); 
     $array = explode(PHP_EOL, $string); 

     $result2 = Myfunction($string, 50); // reads 50 rows of istorija.txt 

     function Myfunction($pavadinimas,$NoOfRows){ 
      For($i=0;$i<=$NoOfRows;$i++){ 
       $returnstr .= $pavadinimas[$i] ."<br>\n"; // this appends the $returnstr with the next row 
      } 
      return $returnstr; // returns it to where the function was called. 
     } 
} 

現在$結果和$ RESULT2是25/50行每個變量的(pavadinimas /串)。

你沒有給我很多去繼續你想要的,你的代碼超出了我所說的。但這可能是你想要的。

+0

或者你可以打開文件並使用'fopen'逐行讀取它。 – Styphon

+0

@Styphon你確定它讀取數組?我對此沒有記憶,也找不到它所做的任何事情。 – Andreas

+0

Positive - http://php.net/manual/en/function.fgets.php#example-2602 – Styphon