2016-12-04 17 views
0

此代碼用於讀取包含100個URL的文本文件的內容,每行一個。該腳本將使用file_get_contents在URL中搜索特定單詞。Php while inside - 這段代碼有什麼問題?

<?php 
$mysearch = file("phpelist.txt"); 

for($index = 0; $index <count($mysearch); $index++) 
{ while ($index >=10 && $index <=20): 

    $mysearch[$index] = str_replace("\n", "", $mysearch[$index]); 
    $data = file_get_contents("$mysearch[$index]"); 

    $searchTerm = 'about'; 

    if (stripos($data, $searchTerm) !== false) { 
     echo "$mysearch[$index]</strong>...FOUND WORD<br><strong>"; 
    } 
    else 
    { 
     echo "$mysearch[$index]</strong>...NO SUCH WORD<br><strong>"; 
    } 
endwhile; 
} 

?> 
+0

'$ index'在'while'裏面沒有被修改一旦進入永不退出 – cske

+2

您確定此代碼在運行嗎?它看起來像你有語法錯誤...使用'endwhile'時,你應該使用'while(...):' – Dekel

+0

並閱讀其他評論以及:) – Dekel

回答

0

您的代碼混淆了我。只看要求聲明,我得到...

$searchTerm = 'about'; 
$file = new SplFileObject('phpelist.txt'); 
foreach ($file as $n => $url) { 
    if ($n < 10) continue; 
    if ($n > 20) break; 

    $content = file_get_contents($url); 
    if (stripos($content, $searchTerm) !== false) { 
     echo "<strong>$url</strong>...FOUND WORD<br>"; 
    } else { 
     echo "<strong>$url</strong>...NO SUCH WORD<br>"; 
    } 
} 

更正:其他要求(見下面的註釋)。這意味着它不再比OP短得多。它唯一增加的,我想是使用SplFileObject。我喜歡使用SplFileObject,因爲它使您可以像使用陣列一樣使用文件(無需將整個文件加載到內存中),因此可用於foreach(因爲SplFileObject實現Iterator接口)。

+0

嗨,我需要腳本來讀取10和20之間的行。對不起,沒有提到這一點。 –

+0

我現在也只是意識到您不是在URL中搜索,而是從該URL中檢索的內容。讓我解決它... – BareNakedCoder