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