【问题标题】:can't get html source code with cUrl or file_get_contents无法使用 cUrl 或 file_get_contents 获取 html 源代码
【发布时间】:2016-12-22 21:52:42
【问题描述】:

抱歉无法获取此url的html源代码:http://www.picbear.com/tag/ok

我总是得到一个带有 ["Hello Stranger"] 消息的空白页。

如果我使用 chrome 的工具没问题。

我一直使用file_get_contentsphp_simple_html DOM 解析器没有任何问题。

由于我的供应商限制,我无法访问 php.ini,但应该没问题。

帮助任何人?谢谢。

$url = "http://www.picbear.com/tag/ok";

$html = file_get_contents($url);

echo $html;

【问题讨论】:

  • 为我工作。你一定是做错了什么。

标签: php html curl file-get-contents source-code-protection


【解决方案1】:

只需添加User-Agent 标头:

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "http://picbear.com/tag/ok",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "cache-control: no-cache",
    "user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36" // Here we add the header
  ),

));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}

【讨论】:

  • 谢谢,你让我开心。抱歉大家的格式不好,但这是我的第一个问题
猜你喜欢
  • 2011-04-05
  • 2017-06-29
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-17
相关资源
最近更新 更多