can't get right api result from json (using json_decode) - php

I want to print result from API...
But it is not working... I don't know what is wrong I tried to do it but got this and it is not working:
<?php
$api = 'https://api.battlemetrics.com/servers/'; // the main API for servers.
$server = '5090469'; // the number of the server you will get the info from most of thime something like 5484856.
$api_full = $api . $server; // bringing them together.
$json = file_get_contents("$api_full"); // Putting the content of the file in a variable.
$response = json_decode($json, true); // decode the JSON feed
if ($response['data']['status'] == "online") {
echo "ONLINE";
} else {
echo "OFFLINE";
};
?>
Extra if you want to see the json response this is the link: https://api.battlemetrics.com/servers/5090469
Thanks in advance for your tips and help.

Looks like you are just missing a key in your if statement.
It should be:
if($response['data']['attributes']['status'] == "online")

Related

Returning value from restAPI in php, echo value not showing

I'm trying to return a value from my API using PHP, api can be found here:
code is as follows:
Im not seeing the echo on my page, don't see any errors and I believing im reading the json in correctly. Any help appreciated!
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$returnvalue = json_decode($response, true);
echo $returnvalue["Age"];
?>
From what I can tell, the json is not valid on the server side (due to the "connected to db" text in front of the {} part). I think it would be a good idea to fix the server side response json data, if possible!
For now, here is a way to get the value it looks like you are intending to retrieve:
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$adjusted_response = str_replace('connected to db', '', $response);
$returnvalue = json_decode($adjusted_response, true);
echo $returnvalue['tv_shows']['Age'];
?>
Output:
$ php example.php
16+
If the server side json data is fixed, I think you could shorten the code to something like this:
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$returnvalue = json_decode($response, true);
echo $returnvalue['tv_shows']['Age'];
?>
The thing is that $response is returned as string , in order to fix that you need to edit your backend and make it give the response without "connected to db"

Get incoming webhook of woocommerce

I'm trying to receive a JSON of a woocommerce webhook in a tracker.php to manipulate the content, but something is wrong because it doesn't save anything in $_SESSION. This is my code ....
(!isset($_SESSION))? session_start() : null;
if($json = json_decode(file_get_contents("php://input"), true)) {
$data = json_decode($json, true);
$_SESSION["json"] = $data;
} else {
var_dump($_SESSION["json"]);
}
tested the webhook with http://requestbin.fullcontact.com/ and received the content. here a capture
issue is in this line
$data = json_decode($json, true);
here $json is array and jsondecode expect string.
here is code which will work.
(!isset($_SESSION))? session_start() : null;
if($json = json_decode(file_get_contents("php://input"), true)) {
//this seection will execute if you post data.
$_SESSION["json"] = $json;
} else {
//this will execute if you do not post data
var_dump($_SESSION["json"]);
}

When i try to get my json echo from an url i have a null response

I currently try to do an api by myself but i have an issue with to get the json data from a page. For now i'm in symfony 3 and what i want to do is return a list of my data to use it in another page. This is what my controller looks like :
$TabConge = array();
if(isset($_GET['all'])){
$conges = $repository->findAll();
foreach ($conges as $value) {
array_push($TabConge,array($value->getId()=>array(
'start_conge' => $value->getStartConge()->format('Y-m-d'),
'end_conge'=>$value->getEndConge()->format('Y-m-d'),
'deadline_conge'=>$value->getDeadlineConge()->format('Y-m-d'),
'first_name'=>$value->getPrenomConge(),
'last_name'=>$value->getNomConge(),
'comment'=>$value->getCommentConge(),
'type_conge'=>$value->getTypeConge(),
}
header('Content-Type: application/json');
echo json_encode($TabConge, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
}
return $this->render('TestApiBundle:Data:find.html.twig');
This shows me the data on my page thanks to the echo :
What my page looks like
But when i try to get then from another page like this :
$json_url = "http://localhost/conge_back/web/app_dev.php/find?all";
$json = file_get_contents($json_url);
$data = json_decode($json, TRUE);
var_dump($data);
I have a "NULL" answer !
Hope u will understand my bad english !

How extract information from a json retrieved from an API?

I'm trying to get somes informations from an API but I always failed.
The API code :
{"matches":[{"matchId":2032325149,"region":"EUW","platformId":"EUW1","matchMode":"CLASSIC","matchType":"MATCHED_GAME","matchCreation":1427400448291,"matchDuration":2225,"queueType":"RANKED_SOLO_5x5","mapId":11,"season":"SEASON2015","matchVersion":"5.6.0.190","participants":[{"teamId":100,"spell1Id":3,"spell2Id":4,"championId":53,"highestAchievedSeasonTier":"UNRANKED","timeline":{"creepsPerMinDeltas":{"zeroToTen":0.9,"tenToTwenty":0.9,"twentyToThirty":0.6,"thirtyToEnd":1.2},"xpPerMinDeltas":{"zeroToTen":253.60000000000002,"tenToTwenty":237.8,"twentyToThirty":477.29999999999995,"thirtyToEnd":448.4},"goldPerMinDeltas":{"zeroToTen":128.2,"tenToTwenty":169.6,"twentyToThirty":310.9,"thirtyToEnd":211.2},"csDiffPerMinDeltas":{"zeroToTen":-0.8,"tenToTwenty":-0.5499999999999998,"twentyToThirty":-1.2499999999999998,"thirtyToEnd":-0.30000000000000027},"xpDiffPerMinDeltas":{"zeroToTen":-12.299999999999983,"tenToTwenty":-127.04999999999998,"twentyToThirty":120.09999999999997,"thirtyToEnd":-491.9},"damageTakenPerMinDeltas":{"zeroToTen":187.2,"tenToTwenty":644.0999999999999,"twentyToThirty":1015.2,"thirtyToEnd":2076.2},"damageTakenDiffPerMinDeltas":{"zeroToTen":9.149999999999963,"tenToTwenty":32.49999999999997,"twentyToThirty":126.24999999999991,"thirtyToEnd":762.9000000000001},"role":"DUO_SUPPORT","lane":"BOTTOM"},"masteries":[{"masteryId":4211,"rank":2},{"masteryId":4213,"rank":2},{"masteryId":4221,"rank":1},{"masteryId":4222,"rank":3},{"masteryId":4232,"rank":1},{"masteryId":4233,"rank":3},{"masteryId":4234,"rank":3},{"masteryId":4244,"rank":1},{"masteryId":4312,"rank":3},{"masteryId":4313,"rank":3},{"masteryId":4322,"rank":1},{"masteryId":4324,"rank":1},{"masteryId":4331,"rank":3},{"masteryId":4334,"rank":1},{"masteryId":4341,"rank":1},{"masteryId":4342,"rank":1}],"stats":{"winner":false,"champLevel":15,"item0":2049,"item1":3401,"item2":3270,"item3":2010,"item4":3110,"item5":3082,"item6":3340,"kills":1,"doubleKills":0,"tripleKills":0,"quadraKills":0,"pentaKills":0,"unrealKills":0,"largestKillingSpree":0,"deaths":11,"assists":10,"totalDamageDealt":31311,"totalDamageDealtToChampions":9198,"totalDamageTaken":31747,"largestCriticalStrike":0,"totalHeal":3600,"minionsKilled":36,"neutralMinionsKilled":0,"neutralMinionsKilledTeamJungle":0,"neutralMinionsKilledEnemyJungle":0,"goldEarned":8264,"goldSpent":8055,"combatPlayerScore":0,"objectivePlayerScore":0,"totalPlayerScore":0,"totalScoreRank":0,"magicDamageDealtToChampions":7159,"physicalDamageDealtToChampions":2038,"trueDamageDealtToChampions":0,"visionWardsBoughtInGame":0,"sightWardsBoughtInGame":0,"magicDamageDealt":22000,"physicalDamageDealt":5572,"trueDamageDealt":3737,"magicDamageTaken":15037,"physicalDamageTaken":16608,"trueDamageTaken":102,"firstBloodKill":false,"firstBloodAssist":false,"firstTowerKill":false,"firstTowerAssist":false,"firstInhibitorKill":false,"firstInhibitorAssist":false,"inhibitorKills":0,"towerKills":0,"wardsPlaced":28,"wardsKilled":1,"largestMultiKill":1,"killingSprees":0,"totalUnitsHealed":4,"totalTimeCrowdControlDealt":445},"participantId":0,"runes":[{"runeId":5273,"rank":9},{"runeId":5289,"rank":9},{"runeId":5317,"rank":9},{"runeId":5357,"rank":3}]}],"participantIdentities":[{"participantId":0,"player":{"summonerId":66366116,"summonerName":"name","matchHistoryUri":"/v1/stats/player_history/EUW1/217404427","profileIcon":690}}]}]}
I'm trying to get "Kills" value and this is my php code :
<?php
$result = file_get_contents('API URL LINK HERE);
$key = json_decode($result);
print '<p><b>' . $key->matches->participants->stats->Kills . '</b></p>';
?>
Please can someone correct my code ?
Thanks a lot.
<?php
$json = '{"matches":[{"matchId":2032325149,"region":"EUW","platformId":"EUW1","matchMode":"CLASSIC","matchType":"MATCHED_GAME","matchCreation":1427400448291,"matchDuration":2225,"queueType":"RANKED_SOLO_5x5","mapId":11,"season":"SEASON2015","matchVersion":"5.6.0.190","participants":[{"teamId":100,"spell1Id":3,"spell2Id":4,"championId":53,"highestAchievedSeasonTier":"UNRANKED","timeline":{"creepsPerMinDeltas":{"zeroToTen":0.9,"tenToTwenty":0.9,"twentyToThirty":0.6,"thirtyToEnd":1.2},"xpPerMinDeltas":{"zeroToTen":253.60000000000002,"tenToTwenty":237.8,"twentyToThirty":477.29999999999995,"thirtyToEnd":448.4},"goldPerMinDeltas":{"zeroToTen":128.2,"tenToTwenty":169.6,"twentyToThirty":310.9,"thirtyToEnd":211.2},"csDiffPerMinDeltas":{"zeroToTen":-0.8,"tenToTwenty":-0.5499999999999998,"twentyToThirty":-1.2499999999999998,"thirtyToEnd":-0.30000000000000027},"xpDiffPerMinDeltas":{"zeroToTen":-12.299999999999983,"tenToTwenty":-127.04999999999998,"twentyToThirty":120.09999999999997,"thirtyToEnd":-491.9},"damageTakenPerMinDeltas":{"zeroToTen":187.2,"tenToTwenty":644.0999999999999,"twentyToThirty":1015.2,"thirtyToEnd":2076.2},"damageTakenDiffPerMinDeltas":{"zeroToTen":9.149999999999963,"tenToTwenty":32.49999999999997,"twentyToThirty":126.24999999999991,"thirtyToEnd":762.9000000000001},"role":"DUO_SUPPORT","lane":"BOTTOM"},"masteries":[{"masteryId":4211,"rank":2},{"masteryId":4213,"rank":2},{"masteryId":4221,"rank":1},{"masteryId":4222,"rank":3},{"masteryId":4232,"rank":1},{"masteryId":4233,"rank":3},{"masteryId":4234,"rank":3},{"masteryId":4244,"rank":1},{"masteryId":4312,"rank":3},{"masteryId":4313,"rank":3},{"masteryId":4322,"rank":1},{"masteryId":4324,"rank":1},{"masteryId":4331,"rank":3},{"masteryId":4334,"rank":1},{"masteryId":4341,"rank":1},{"masteryId":4342,"rank":1}],"stats":{"winner":false,"champLevel":15,"item0":2049,"item1":3401,"item2":3270,"item3":2010,"item4":3110,"item5":3082,"item6":3340,"kills":1,"doubleKills":0,"tripleKills":0,"quadraKills":0,"pentaKills":0,"unrealKills":0,"largestKillingSpree":0,"deaths":11,"assists":10,"totalDamageDealt":31311,"totalDamageDealtToChampions":9198,"totalDamageTaken":31747,"largestCriticalStrike":0,"totalHeal":3600,"minionsKilled":36,"neutralMinionsKilled":0,"neutralMinionsKilledTeamJungle":0,"neutralMinionsKilledEnemyJungle":0,"goldEarned":8264,"goldSpent":8055,"combatPlayerScore":0,"objectivePlayerScore":0,"totalPlayerScore":0,"totalScoreRank":0,"magicDamageDealtToChampions":7159,"physicalDamageDealtToChampions":2038,"trueDamageDealtToChampions":0,"visionWardsBoughtInGame":0,"sightWardsBoughtInGame":0,"magicDamageDealt":22000,"physicalDamageDealt":5572,"trueDamageDealt":3737,"magicDamageTaken":15037,"physicalDamageTaken":16608,"trueDamageTaken":102,"firstBloodKill":false,"firstBloodAssist":false,"firstTowerKill":false,"firstTowerAssist":false,"firstInhibitorKill":false,"firstInhibitorAssist":false,"inhibitorKills":0,"towerKills":0,"wardsPlaced":28,"wardsKilled":1,"largestMultiKill":1,"killingSprees":0,"totalUnitsHealed":4,"totalTimeCrowdControlDealt":445},"participantId":0,"runes":[{"runeId":5273,"rank":9},{"runeId":5289,"rank":9},{"runeId":5317,"rank":9},{"runeId":5357,"rank":3}]}],"participantIdentities":[{"participantId":0,"player":{"summonerId":66366116,"summonerName":"name","matchHistoryUri":"/v1/stats/player_history/EUW1/217404427","profileIcon":690}}]}]}';
$data = json_decode($json, true);
echo $data['matches'][0]['participants'][0]['stats']['kills'];
?>

Using php for http requests

I am very new to PHP, and need to use an HTTP Request to download a URL that is external to my server. That URL is a PHP function that returns JSON code which I have decode. Any suggestions?
I have tried basic code:
<?php
//Code for forming the url (which I'm sure is correct)
$url = ...
$response = fopen($url,"x+");
$response = json_decode($response);
echo $response;
?>
//javascript in a seperate file that calls the php code
var response = xmlhttp.responseText;
alert(response);
Try this:
<?php
$url = 'YOUR_URL_HERE';
$data = file_get_contents( $url ); // it is a JSON response as per your statement.
$data= json_decode($data);
print_r($data); // now, it's a normal array.
?>
You may use fopen if config allows, or cURL or fsockopen functions to do that
You could use:
$json_str = file_get_contents($url);
$json = json_decode($json_str, true);
Couldn't you use file_get_contents? E.g.
<?php
$url = "YOUR_URL";
$json = file_get_contents($url);
// handle the data
$data = json_decode($json, TRUE);
var_dump($data); // example
?>
If you are doing a lot of requests you can try using a http class like Buzz which will Help clean up your code https://github.com/kriswallsmith/Buzz

Categories