Ra afni
Ra afni

Reputation: 51

How to get result of JSON use cURL?

i want to get result json from rest api of youtube with this code

<?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);

?>

but i just get NULL result how to fix it ?

Upvotes: 1

Views: 76

Answers (1)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38542

Try like this way to capture the error.By the way, your existing code works fine for me, I guess you don't have the php curl installed. SEE 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;
}
?>

EDIT: If you got the SSL issue then set this two lines on your existing code

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

Upvotes: 2

Related Questions