如何使用cURL获取JSON结果?

时间:2019-02-13 10:01:07

标签: php json

我想使用此代码从youtube的REST API获取结果json

<?php
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_URL,'https://www.googleapis.com/youtube/v3/channels?part=snippet,statistics&id=UCkXmLjEr95LVtGuIm3l2dPg&key=AIzaSyB1Xn7nMC1dH04rrMVDcMYICjhM4wWvE0k' );
  curl_setopt($curl,  CURLOPT_RETURNTRANSFER, true );
  $result = curl_exec($curl);
  curl_close($curl);

  $result = json_decode($result, true);
  var_dump($result);

?>

但是我只是得到NULL结果如何解决?

1 个答案:

答案 0 :(得分:2)

尝试以这种方式捕获error。通过这种方式,您现有的代码对我来说很好用,我想您没有安装php curl。 请参阅 curl_error()

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://www.googleapis.com/youtube/v3/channels?part=snippet,statistics&id=UCkXmLjEr95LVtGuIm3l2dPg&key=AIzaSyB1Xn7nMC1dH04rrMVDcMYICjhM4wWvE0k",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

if ($err) {
  echo "cURL Error #:" . $err;
} else {
  echo $response;
}
?>

编辑:如果遇到 SSL 问题,请在您的现有代码上设置这两行

curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);