PHP - 使用 CURL 获取文件内容

标签 php curl

我有一个关于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;
}

最佳答案

对于curl,使用 curl_getinfo 通常是个好主意在关闭 curl 连接之前获取有关 curl 连接的其他信息。在您的情况下,NULL/FALSE/空结果可能是由于多种原因造成的,检查 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检查。

关于PHP - 使用 CURL 获取文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49576753/

相关文章:

php - index.php# 不同于 index.php

curl - ASP.NET MVC curl 等价物

php - 使用 Guzzle 但不是通过浏览器或命令行 cURL 或 wget 时出现 406

PHP:用于存储在 MySQL 数据库中的 json_encode 与序列化?

php - 使用 mysql 的查询从 php 输出 pdf

php - 迁移到新的 PHP 服务器时出现文件夹路径问题。文件夹/../文件夹2

curl: (35) SSL 连接错误,NSS 错误 -5938

javascript - 尝试自动访问使用 Javascript 加密表单数据的 Web 界面

java - 如何将简单的 Curl 调用转换为 Java HttpURLConnection

python - 将 cURL 转换为 Python - 上传文件