gpt4 book ai didi

php - file_get_contents 脚本适用于某些网站,但不适用于其他网站

转载 作者:可可西里 更新时间:2023-11-01 00:25:53 24 4
gpt4 key购买 nike

我正在寻找构建一个 PHP 脚本来解析特定标记的 HTML。我一直在使用这个代码块,改编自这个 tutorial :

<?php 
$data = file_get_contents('http://www.google.com');
$regex = '/<title>(.+?)</';
preg_match($regex,$data,$match);
var_dump($match);
echo $match[1];
?>

该脚本适用于某些网站(如上面的 google),但当我尝试使用其他网站(如 freshdirect)时,我收到此错误:

“警告:file_get_contents( http://www.freshdirect.com ) [function.file-get-contents]: 无法打开流:HTTP 请求失败!”

我在 StackOverflow 上看到了很多很棒的 suggestions,例如在 php.ini 中启用 extension=php_openssl.dll。但是 (1) 我的 php.ini 版本中没有 extension=php_openssl.dll,并且 (2) 当我将它添加到扩展部分并重新启动 WAMP 服务器时,根据这个 thread ,仍然没有成功。

有人介意给我指明正确的方向吗?非常感谢你!

最佳答案

它只需要一个用户代理(实际上是“任何”,任何字符串都可以):

file_get_contents("http://www.freshdirect.com",false,stream_context_create(
array("http" => array("user_agent" => "any"))
));

参见 more options .

当然可以设置user_agent在你的 ini 中:

 ini_set("user_agent","any");
echo file_get_contents("http://www.freshdirect.com");

...但我更愿意为下一个从事此工作的程序员明确说明。

关于php - file_get_contents 脚本适用于某些网站,但不适用于其他网站,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6902955/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com