0

Basically I'm trying to GET an API that gives me a JSON array. It should only be one integer. Whenever I try to though I receive the error:

Notice: Trying to get property of non-object in /public_html/call.php on line 16

Here's call.php:

    <?php
require 'connection.php';

$players2weeks = '(removed api)';


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $players2weeks);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

$response = curl_exec($ch);
curl_close($ch);

$response = json_decode($response);

print_r($response);
echo $response->players_2weeks;
?>

I have the print_r for troubleshooting but I'm getting nothing. My apologies for a noob question by the way, I have no experience with JSON.

Appreciate the help!

ksakskfk
  • 9
  • 1
  • 3

2 Answers2

0

I think you can use this Code :

<?php
require 'connection.php';

$players2weeks = '(removed api)';


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $players2weeks);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);

$response = curl_exec($ch);
curl_close($ch);

$responses = json_decode($response);

print_r($responses);
echo $responses['players_2weeks'];
?>

You should change the format of echo when the decoded JSON objects. and the Variable same means some clashes in the print so I changed the $response variable also...

Nawin
  • 1,653
  • 2
  • 14
  • 23
  • Thanks for the reply, however, still not receiving any input and it isn't working in a formula. Here's my formula code: require 'call.php'; $player2weeks_result = $responses; $a = 1; $b = 2; $formula = ($player2weeks_result-($player2weeks_result*$a))-(($player2weeks_result-($player2weeks_result*$a))*$b); echo $formula; – ksakskfk May 30 '17 at 05:04
  • Change to your `$player2weeks_result = $responses` to this `$player2weeks_result = $responses['players_2weeks']` – Nawin May 30 '17 at 05:09
  • What is the result you get when print `echo $responses['players_2weeks'];` this? – Nawin May 30 '17 at 05:10
  • please post your JSON print – Nawin May 30 '17 at 05:12
  • print_r($player2weeks_result) doesn't show anything – ksakskfk May 30 '17 at 05:15
  • Am telling `print_r($responses);` – Nawin May 30 '17 at 05:16
  • That also returns nothing. I think it might be an API problem. Is there a good way to confirm? – ksakskfk May 30 '17 at 05:18
-1

You have to make array to json string by using the json_encode() function on the api.

For example: xxx.php (api)

$result = array(); //return array
echo json_encode($result);

Then you can get result by json array on the api caller.

var_dump(json_decode($result));           // Object
var_dump(json_decode($result, true));     // Associative array
Mang Tang
  • 1
  • 3