2013-04-09 47 views
-1

嗨只有一條線,我有這個文件test1.php和其他文件test.php我有這樣的 php代碼運行:獲得從網頁

<?php 
$file = "http://inviatapenet.gethost.ro/sop/test1.php"; 
$line = '0'; 
if($f = fopen($file, 'r')){ 
    $line = fgets($f); // read until first newline 
    fclose($f); 
} 
echo $line; 
?> 

的想法是得到公正的第二行網頁test1.php。

二線

我試圖改變$line = '2';但沒有影響,它只是顯示的第一道防線。 我需要幫助。

+0

權,因爲你只是'第一行',你就是n不要在任何地方使用你的'$ line'變量。嘗試在循環中使用它。 – deceze 2013-04-09 09:13:46

回答

0

這應該工作。顯然,改變的僅$linetofetch值:

<?php 
// Write here the number of the line you want to fetch. 
$linetofetch = 2; 

$file = "http://inviatapenet.gethost.ro/sop/test1.php"; 
$currentline = 1; 
if($f = fopen($file, 'r')){ 
    while ($currentline <= $linetofetch) { 
    $line = fgets($f); // read until first newline 
    $currentline++; 
    } 
    fclose($f); 
    } 
echo $line; 
?> 
+0

這不可能!它給我錯誤:fclose():3不是一個有效的流資源 – 2013-04-09 09:30:55

+0

對不起,'fclose'不得不在外面的循環,糾正,但戴爾答案是更好的反正( – 2013-04-09 10:06:52

+0

但你的迴應幫助我更好 – 2013-04-09 10:33:20

1

您可以使用file讀取一個文件到一個數組,然後你可以抓住你需要的任何行用你想要的索引。

例如:

的data.txt:

line one 
line two 
line three 
line four 

PHP代碼:新版本

$file = file('data.txt'); 
echo $file[1]; // echo line number 2, remember arrays start at 0! 

更新PHP代碼(5.4):

echo file('data.txt')[1]; 
+0

不錯,+1,因爲我什至不知道這個,5.4的版本應該更有效率,對吧?(因爲沒有文件實際存儲到變量中) – 2013-04-09 09:21:07

+1

我認爲是的,也是一個這是一個很酷的點上的方式:)) – Dale 2013-04-09 09:23:28

+0

這種煩人的格里特! – 2013-04-09 09:32:44