【问题标题】:PHP 500 internal server error file_get_contentsPHP 500 内部服务器错误 file_get_contents
【发布时间】:2014-06-08 02:38:45
【问题描述】:

我正在尝试使用 PHP 抓取网站页面,然后自动抓取图像。

我尝试了以下方法:

<?php
$url = "http://www.domain.co.uk/news/local-news";

$str = file_get_contents($url);
?>

<?php
    $opts = array('http'=>array('header' => "User-Agent:Mozilla/5.0 (Windows NT 6.2) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.75 Safari/537.1\r\n"));
    $context = stream_context_create($opts);
    $header = file_get_contents('http://www.domain.co.uk/news/local-news',false,$context);
?>

还有

<?php
include('simple_html_dom.php');

$html = file_get_html('http://www.domain.co.uk/news/local-news');

$result = $html->find('section article img', 0)->outertext;
?>

但是这些都返回Internal Server Error。我可以在浏览器中完美地查看该网站,但是当我尝试在 PHP 中抓取该页面时失败了。

有什么我可以尝试的吗?

【问题讨论】:

标签: php file-get-contents


【解决方案1】:

试试下面的代码:它将内容保存在本地文件中。

<?php
$ch = curl_init("http://www.domain.co.uk/news/local-news");
$fp = fopen("localfile.html", "w");
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

现在你可以准备好localfile.html了。

【讨论】:

  • 这成功创建了一个文件,但是当我尝试通过在您的代码下添加以下内容来访问它时,它会覆盖 localfile.html 并返回 500 Error include('simple_html_dom.php'); $html = file_get_html('http://domain.com/build/wp-content/plugins/news-plugin/localfile.html'); $result = $html-&gt;find('.lead-story', 0)-&gt;outertext; echo $result;
  • 为什么在我使用的服务器中收到错误 500?
【解决方案2】:

有时您可能会在使用 file_get_contents 打开 http URL 时遇到错误。 即使您在 php.ini

中设置了 allow_url_fopen = On

对我来说,解决方案是将“user_agent”也设置为某个值。

【讨论】:

  • 更好:使用 cUrl。许多主机阻止使用 file_get_contents。
猜你喜欢
  • 2012-08-08
  • 1970-01-01
  • 1970-01-01
  • 2018-01-15
  • 2010-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-04
相关资源
最近更新 更多