So I'm (very) new to the API and I'm basically just trying to get it to make a call and print the result. I've been at it for almost 8 hours now and I'm getting nowhere. I feel like this should work but I get no response at all. What am I doing wrong?
<html>
<head>
<title>Testing</title>
</head>
<body>
<?php {
$url = "https://api.torn.com/user/2167054?selections=profile&key=APIkeyHere";
$json = file_get_contents($url);
$apidata = json_decode($json, true);
} ?>
<pre>
<?php print_r($apidata); ?>
</pre>
</body>
</html>
Any input would be much appreciated!
I haven't done PHP for ages but what's the {} around the declaration of your variables?
If it's like c++ the variables will be defined only inside {}... so the $apidata will be empty in the print_r.
Otherwise you can set your server to different level of verbose. If you set it to display even notices you've got a chance to see your problem showing up. I remember mine by default was only showing errors which is not handy for dev.
Yeah just <?php ... ?>, not <?php { ... } ?>
Oh yes of course... I'm so blind sometimes. Thank you, that worked!
My current code for calling TornAPI via PHP:
/**
* Retreives torn data from Torn API.
*
* @param string $api_key
* Torn API key.
* @param int $player_id
* Player ID to query at the Torn API.
* @param string $type
* Torn API query type.
* @return string $response
* Torn API response.
*/
public static function CallTorn($api_key, $player_id, $type, $selection = null)
{
$url = "https://api.torn.com/" . $type . "/" . $player_id . "?";
$params = [
'selections' => $selection,
'key' => $api_key,
];
$defaults = [
CURLOPT_URL => $url . http_build_query($params),
CURLOPT_RETURNTRANSFER => true,
];
$curl = curl_init();
curl_setopt_array($curl, $defaults);
$response = json_decode(curl_exec($curl));
// Add cached time to returned object to reduce the number of API calls.
$response->cached_time = time();
curl_close($curl);
return $response;
}