首页 > 解决方案 > 我收到 NULL 数据以响应 cURL 请求

问题描述

我正在做一个 cURL 请求以使用 api 获取信息,但是当我使用 json_decode 时,它​​没有提供任何信息,而是返回 NULL 值。请通过这些线路-

//  Initiate curl
 $ch = curl_init();
// Disable SSL verification
 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,"http://mkp.gem.gov.in/oem-cartridge/samsung-111s-toner-rst/p-5116877-68482402616-cat.html");
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

//  Will dump a beauty json :3
var_dump(json_decode($result, true));

这是使用 API 发出 cURL 请求和获取信息的正确方法,还是建议我如何做,因为我是这个主题的新手。

标签: phpjquerycurl

解决方案


您的以下代码行

$result=curl_exec($ch);

返回301 永久移动

因为您的 URL 仅使用 HTTP http://mkp.gem.gov.in/oem-cartridge/samsung-111s-toner-rst/p-5116877-68482402616-cat.htm

但是此站点在 HTTPS 上运行,并且服务器已设置为强制/将此仅 HTTP 的 URL 重定向到 HTTPS,即 https://mkp.gem.gov.in/oem-cartridge/samsung-111s-toner-rst/p-5116877-68482402616-cat.html

您可以将您的 url 更改为 https 或使用以下方式设置跟随重定向 true

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // follow redirect if any

但它仍然呈现 HTML 而不是 JSON。

但是在您的评论中,您说这个相同的 URL 正在与节点一起使用,在这种情况下,请交叉检查您的 URL 或尝试使用 POSTMAN 发出相同的请求并查看显示的内容


推荐阅读