我正在努力学习如何创建网络机器人,我正在通过Michael Schrenk的一本名为 Webbots,Spiders和Screen Scrapers 的书来学习。在本书中,他给出了下载网页的基本机器人的示例代码。我已经完全按照书中的原样复制了代码(没有评论):
<?
$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);
我已检查过该网址,以确保该文件存在且确实存在。我不知道为什么这不起作用。我已经阅读了如何使用file();和fopen(); PHP中的函数,但据我所知,它们都被正确使用。我在这里做错了什么?
答案 0 :(得分:0)
首先,您应该将error_reporting(E_ALL); ini_set('display_errors', '1');
添加到您的脚本中,以便在AbraCadaver的评论中提到您的脚本中显示错误。
原因可能是,您的托管已禁用allow_url_fopen
。
此选项启用支持URL的fopen包装器,以便访问类似文件的URL对象。提供了使用ftp或http协议访问远程文件的默认包装器,像zlib这样的扩展可能会注册其他包装器。
请参阅:http://php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen
您可以通过以下方式检查:
var_dump(ini_get('allow_url_fopen'));
您的脚本需要true
才能正确运行。
如果allow_url_fopen
不是true
或1
,您可以尝试使用file_get_contents()
加载网址。
<?php
$homepage = file_get_contents('http://www.example.com/');
echo $homepage;
?>
答案 1 :(得分: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 );
答案 2 :(得分:0)
通过fopen()
访问网址是糟糕的主意。它要求您在PHP配置中启用allow_url_fopen
,这为大量漏洞打开了大门(托管人因某种原因禁用它)。
请尝试使用cURL functions:它们将为您提供更多灵活性和控制力。 PHP文档为您提供了一些great examples开始。