使用cURL获取NULL,但使用file_get_contents()获取数组


getting NULL with cURL but Array with file_get_contents()

我有CURL从链接的问题。我可以得到file_get_contents();的输出但是CURL

有问题

使用json_decode我得到一个NULL与cURL,但与file_get_contents()我得到一个数组

使用cURL

$url="https://example.com/" 
$ch= curl_init(); 
curl_setopt($ch, CURLOPT_URL,$url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$json= json_decode(curl_exec($ch),true); 
echo $json; //outputs NULL

使用file_get_contents();

$json_pi = file_get_contents($url); 
echo json_decode($json_pi,true);

谁能帮我理解cURL?为什么我可能会得到这两个相互矛盾的结果?

谢谢!

在调用之后没有做任何错误检查,所以如果出现问题,您将永远不会听到它。

  • 使用curl_error()

  • 检查CURL调用的结果
  • 使用json_last_error() (PHP>= 5.3)

  • 检查json_encode()调用的结果

其中之一可能会揭示问题所在。例如,curl调用可能会获取非UTF-8字符集的数据,这将导致json_decode()中断—它始终期望使用UTF-8数据。