【问题标题】:PHP - file get contents using CURL [duplicate]PHP - 使用 CURL 获取文件内容
【发布时间】:2018-09-09 15:10:48
【问题描述】:

我的 curl 有问题,我尝试使用 CURL 获取内容但只返回 null,我不知道我错过了什么,请告诉我,这是我的代码:

$url = "https://shopee.co.id/api/v1/search_items/?by=pop&order=desc&keyword=yi 067&newest=0&limit=50&page_type=shop&match_id=16775174";
$html = file_get_contents_curl($url);
var_dump($html);

function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_ENCODING, 0);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST , "GET");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);  
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json'));


    $data = curl_exec($ch);
    curl_close($ch);

    return $data;
}

【问题讨论】:

  • 您缺少一些错误报告。我猜是 SSL。
  • 你应该看到这个答案:a link
  • 我使用了这个确切的代码并得到了一些 HTML,但是那个 html 定义了一个包含正文内容的简单文档。 @CSM 你确定它返回的是 NULL 而不是 FALSE 或空字符串?

标签: php curl


【解决方案1】:

使用 curl,在关闭 curl 连接之前使用curl_getinfo 获取有关您的 curl 连接的其他信息通常是一个好主意。在您的情况下,NULL/FALSE/empty 结果可能是由于多种原因,检查 curl 信息可能会帮助您找到更多详细信息。这是您的函数的修改版本,它使用此函数来获取附加信息。您可能会考虑将print_r($info, TRUE) 写入日志文件或其他内容。它可能为空,因为服务器响应为空。这可能是错误的,因为由于防火墙问题,无法从您的服务器访问该 URL。它可能会返回 404 NOT FOUND 或 5XX 的 http_code

function file_get_contents_curl($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_ENCODING, 0);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST , "GET");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);  
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));

    $data = curl_exec($ch);

    $info = curl_getinfo($ch);


    if(curl_errno($ch)) {
        throw new Exception('Curl error: ' . curl_error($ch));
    }

    curl_close($ch);

    if ($data === FALSE) {
        throw new Exception("curl_exec returned FALSE. Info follows:\n" . print_r($info, TRUE));
    }

    return $data;
}

编辑:我也添加了 curl_errno 检查。

【讨论】:

  • 我不知道,但我尝试仍然为空
  • @CSM 我编辑了我的帖子并添加了 curl_errno 错误检查。试试那个功能。老实说,如果您收到 NULL 值,我会感到惊讶。应该是空字符串吧?
  • 非常感谢@S大师。 lmp 昨天这很好:)
猜你喜欢
  • 1970-01-01
  • 2011-08-16
  • 1970-01-01
  • 2011-04-05
  • 2013-07-18
  • 2012-09-28
  • 1970-01-01
  • 2016-05-28
  • 2014-11-29
相关资源
最近更新 更多