jamadri
jamadri

Reputation: 956

cUrl is returning JSON string, json_decode isn't decoding it to object or array

I'm using github's api to pull the most popular "starred" items under PHP, and it's pulling the json string ok. Only issue is my json_decode is still just dumping the JSON string and not an object. Below is the function I'm running.

private function fillTable(){
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL       => 'https://api.github.com/search/repositories?q=+language:php&sort=stars&order=desc',
  CURLOPT_USERAGENT => 'trickell'
));
$res = curl_exec($curl);
var_dump(json_decode($res));
}

I'm not exactly sure why it's not decoding the json string to an object. If you run this you should be able to see exactly what's pulling.

Upvotes: 3

Views: 5586

Answers (3)

lucasvm1980
lucasvm1980

Reputation: 682

You are missing this:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Accept: application/json'
        ));

Upvotes: 0

Siddharth Shukla
Siddharth Shukla

Reputation: 1131

<?php
$post = ['batch_id'=> "2"];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://example.com/student_list.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
$result = json_decode($response);
$new=   $result->status;
if( $new =="1")
{
  echo "<script>alert('Student list')</script>";
}
else 
{
  echo "<script>alert('Not Removed')</script>";
}

?>

Upvotes: 0

Hanky Panky
Hanky Panky

Reputation: 46900

Because you have no json to decode and that is because you are not telling cURL to return the value to you so you are trying to decode an empty string.

$res = curl_exec($curl);

That $res is going to be only TRUE / FALSE unless you ask for RETURNTRANSFER, as explained here

curl_exec

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

So you have to add another option to your cURL call.

curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

You may ask then why are you seeing the JSON string if it is not being returned, this answers that question

CURLOPT_RETURNTRANSFER

TRUE to return the transfer as a string of the return value of curl_exec() instead of outputting it out directly.

(emphasis mine)

Upvotes: 4

Related Questions