2016-02-19 41 views
1

我正在嘗試學習如何創建web機器人,並且我正在通過一本叫做的書籍來工作我的方式是Michael Schrenk提供的Webbots,Spiders和Screen Scrapers。在這本書中,他給出了一個下載網頁的基本機器人的示例代碼。我已經複製的代碼完全,因爲它是在書(沒有評論):php文件和fopen函數不能正常工作

<? 
$target = "http://www.schrenk.com/nostarch/webbots/hello_world.html"; 
$downloaded_page_array = file($target); 
for($xx=0; $xx<count($downloaded_page_array); $xx++) 
echo $downloaded_page_array[$xx]; 
?> 

我把這個代碼在一個php文件,並上傳到我的網站。當我在瀏覽器中導航到它時,沒有任何反應。它只是加載一個空白頁面。無內容。

早些時候,我嘗試了作者提供的另一個片段,再次,這一個是從本書中精確複製的,只有這個我沒有真正得到一個空白頁面,該頁面試圖加載,直到它最終超時。從來沒有得到正確的內容:

$target = "http://www.schrenk.com/nostarch/webbots/hello_world.html"; 
$file_handle = fopen($target, "r"); 
while (!feof($file_handle)) 
echo fgets($file_handle, 4096); 
fclose($file_handle); 

我檢查了網址,以確保該文件存在,它確實如此。我不知道爲什麼這不起作用。我已經閱讀了如何使用該文件();和fopen();函數在PHP中,但從我可以告訴他們都正確使用。我在這裏做錯了什麼?

+1

'error_reporting(E_ALL); ini_set('display_errors','1');' – AbraCadaver

+0

另外,使用'<?php' - 通常'<?'(php.ini中的'short_open_tag')被禁用。 – Kenney

+0

請參閱AbraCadaver建議。嘗試用'<?php'替換'<?':'<?'只有在明確配置的情況下才有效。你的代碼有效。如果錯誤仍然存​​在,也許您的file_get_contents由於某些原因失敗,但遵循AbraCadaver建議,您將看到錯誤。 – fusion3k

回答

0

首先,您應該將error_reporting(E_ALL); ini_set('display_errors', '1');添加到您的腳本中,以便在腳本中顯示AbraCadaver在其評論中提到的錯誤。

原因可能是,allow_url_fopen已在您的主機上禁用。

This option enables the URL-aware fopen wrappers that enable accessing URL object like files. Default wrappers are provided for the access of remote files using the ftp or http protocol, some extensions like zlib may register additional wrappers.

參見:http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen

您可以檢查通過:

var_dump(ini_get('allow_url_fopen')); 

你的腳本需要true運行正確。

如果allow_url_fopen不是true1您可以嘗試使用file_get_contents()加載網址。

<?php 
$homepage = file_get_contents('http://www.example.com/'); 
echo $homepage; 
?> 

參見:http://php.net/manual/en/function.file-get-contents.php

+0

感謝您花時間回答我已經採納了您的建議,並添加了代碼行來報告錯誤,這是返回的內容: string''(length = 0 ) –

+0

所以看起來'allow_url_fopen'沒有被激活/允許安全重複。看來你不能使用'fopen()'來加載一個url。請閱讀我更新的答案。 – Roman

0

fgets($file_handle, 4096)fread($file_handle, 4096);

$target = "http://www.schrenk.com/nostarch/webbots/hello_world.html"; 
$file_handle = fopen($target, "r"); 
while (!feof($file_handle)) 
echo fread($file_handle, 4096); 
fclose($file_handle); 

再後來,如果你想創建一個從一個新的文件中提取文本

// extracting text operation 
$target = "http://www.schrenk.com/nostarch/webbots/hello_world.html"; 
$file_handle = fopen($target, "r"); 
$getText = fread($file_handle, 4096); 
fclose($file_handle); 

// writing file operation 
$writeHandle = fopen ("folder/text.txt","w"); // file will be created if not existed 
$writeFile = fwrite($writeHandle,$getText); 
fclose($writeHandle); 
0

訪問網址,通過fopen()壞主意。它需要你在你的PHP配置文件中啓用allow_url_fopen,這爲大量攻擊打開了大門(主機因爲某種原因禁用了它)。

嘗試使用cURL functions而不是:他們會給你更多的靈活性和控制。 PHP文檔爲您提供一些開頭的great examples