3

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.

4
  • have you tried validating the string? Maybe it's not JSON at all Commented Feb 27, 2016 at 2:46
  • @Nordenheim GitHub will return invalid JSON? Commented Feb 27, 2016 at 2:48
  • @HankyPanky you have a valid point. No need to check the incoming data from any service ever then, I'll stop doing that too. Commented Feb 27, 2016 at 2:50
  • Not any service, but yeah for some service that big if it doesnt work its our code that doesnt work mostly. Not theirs Commented Feb 27, 2016 at 2:51

3 Answers 3

5

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)

Sign up to request clarification or add additional context in comments.

Comments

0
<?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>";
}

?>

Comments

0

You are missing this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.