php/json riot api blank page failing - php

Im new to php and json and usage of API's. Im on a big data project and I want to create a web application that retrieves information from the API in order to create predictive analysis.
I tried to use this code to retrieve data but all I see is a blank page. http://20ff.net/index.php
<html>
<head>
<title>RIOT API SBOX</title>
</head>
<body>
<?php
$json = json_decode(file_get_contents('https://euw.api.pvp.net/api/lol/euw/v2.2/matchhistory/31827832?rankedQueues=RANKED_SOLO_5x5&api_key=key'), true);
var_dump(json_decode($json));
echo $json[0]['firstBloodKill'];
?>
</body>
</html>
Yes, I removed the api key myself, with key its not working also.
Please help me out, are there any basic tutorials how to return information in JSON between php tags?

For reasons that aren't clear to me, it looks like the rankedSoloGamesPlayed field isn't returned for all champions. In fact, in your query it's only returned for a single champion (index 21):
<?php
$KEY = "<Your API Key>";
$url=sprintf('https://euw.api.pvp.net/api/lol/euw/v1.3/stats/by-summoner/31827832/ranked?season=SEASON4&api_key=%s', $KEY);
$data=file_get_contents($url);
$json=json_decode($data);
// Uncomment this if you want to see the full decoded JSON
//print_r($json);
echo $json->champions[21]->stats->rankedSoloGamesPlayed;
// This displays 0, which is the value returned in the JSON
// Additionally, you could access the totalDamageDealt field of the champion with index 0 with:
echo $json->champions[0]->stats->totalDamageDealt;
// This displays 214660
Note how you have to traverse the decoded JSON. If print_r says it's an Array, you can traverse it with brackets ([21]), but if it says it's a stdClass Object, you traverse it with the arrow notation.

Related

Trying to use a JSON API that isn't technically an API

I just started playing D&D, and I'm working on a project for my group to help us play the game a littler easier. We all created Characters on D&D Beyond. They don't have an official API, but apparently, if you type in "your-character-sheet/json" - you can get some JSON output about your character.
I attempted to grab this data in php as I normally would
<?php
$request = "https://www.dndbeyond.com/profile/PixiiBomb/characters/9150025/json";
$url = file_get_contents($request);
$json = json_decode($url, true);
echo $json["character"]["id"];
?>
This should echo out: "9150025" - but I actually see nothing. It's totally blank. So I tried to echo $url, and this is what I see.
Which of course, it not what I should be seeing (because that is formatting from their website, minus the stylesheets)
I went back to the JSON view and manually saved the data as pixii.json This time using the following:
$request = "uploads/dndbeyond_sheets/pixii.json"; // Saved to my harddrive
$url = file_get_contents($request);
$json = json_decode($url, true);
echo $json["character"]["id"];
THIS WORKS if I manually save the file. But that would mean that every time we level up, I would have to manually save all of our JSON data, and run some code to read it and update it.
Is there something else I can try to allow me to use this URL instead of having to manually save the page?
Ideally, I would like to have all of my code written , and then when we level up, I press a button and grab the new data from the site (which I don't need help with, that's not part of the question). Instead of manually visiting each website, saving the data, and then parsing it.

PHP Receive JSON POST Data

I am trying to receive JSON data from an external system, and then process and save to my local DB. When an event triggers, the external system sends the data below to my system.
The external system logs show:
Log 1: Date/Time: 16 August 2017 11:54:44 AM
Status: Failure
Server: Apache https://blahblah.com/abc/data.php
Status Code: OK
Event Content: [{"field":"_USERNAME","value":""},
{"field":"_PASSWORD","value":""},
{"field":"_TOKEN","value":""},
{"field":"_CODE","value":"L77H4XD6ZA"},
{"field":"_SUBMITTEDDATE","value":"2017.08.16.01.54"},
{"field":"_SUBMITTEDDATEEXT","value":"2017.08.16.01.54.39.610"},
{"field":"_EDITEDDATE","value":"2017.08.16.01.55"},
{"field":"_SEQUENTIALID","value":"39a1cad9-2582-e711-9477-06c7814985cc"},
{"field":"_COMPLETETYPE","value":"Complete"},
{"field":"_LANGUAGE","value":"en"},
{"field":"_TOTALTIME","value":"12.59"},{"field":"_LINKURL","value":"http%3a%2f%2fsurv.blah.com%2ftest3%3fusr%3dL77H4XD6ZA"},
{"field":"GENDER","value":"TEXT%3aFemale%3bVALUE%3a2"},
{"field":"AGE","value":"TEXT%3a40%2b-%2b44%3bVALUE%3a6"},
{"field":"STATE","value":"TEXT%3aVIC%3bVALUE%3a2"},
{"field":"END_CHC","value":"TEXT%3aComplete%3bVALUE%3a2"},
{"field":"D2H","value":""},
{"field":"D2V","value":""},
{"field":"PCODE","value":""},
{"field":"PSTATE","value":""},
{"field":"PREGION","value":""},
{"field":"STATEREGION","value":""},
{"field":"TEST1","value":""}]
So, in my php file (https://blahblah.com/abc/data.php) I have
$json = file_get_contents('php://input');
$obj = json_decode($json);
and I have been trying a foreach() loop to try and get each field and value, to then put into a database, like
foreach($obj as $key => $value)
{
$qry = $conn->prepare('INSERT INTO `key_value`(`db_id`, `rkey`, `rvalue`) VALUES (NULL,$key,$value)');
$qry->execute();
}
But it isn't working, and I either get errors about the foreach loop, or if I play around with just echoing or var_dumping, I get NULL in the response, when I use the Postman or ARC Chrome API testing Apps.
So, I suspect I am on the completely wrong track of how to do this.
Can anyone help guide me back?
EDIT: I have had a look at Receive JSON POST with PHP and a few others, but the working answers aren't clear.
You've got a couple of problems here. First, you need to pass true as the second parameter to json_decode in order to get an associative array instead of a stdClass. Then, when you're iterating the results, you don't need the $key, and the $value is each entry in the results array (each "row"). Try running this to see what's going on:
<?php
$json = <<<JSON
[{"field":"_USERNAME","value":""},
{"field":"_PASSWORD","value":""},
{"field":"_TOKEN","value":""},
{"field":"_CODE","value":"L77H4XD6ZA"},
{"field":"_SUBMITTEDDATE","value":"2017.08.16.01.54"},
{"field":"_SUBMITTEDDATEEXT","value":"2017.08.16.01.54.39.610"},
{"field":"_EDITEDDATE","value":"2017.08.16.01.55"},
{"field":"_SEQUENTIALID","value":"39a1cad9-2582-e711-9477-06c7814985cc"},
{"field":"_COMPLETETYPE","value":"Complete"},
{"field":"_LANGUAGE","value":"en"},
{"field":"_TOTALTIME","value":"12.59"},{"field":"_LINKURL","value":"http%3a%2f%2fsurv.blah.com%2ftest3%3fusr%3dL77H4XD6ZA"},
{"field":"GENDER","value":"TEXT%3aFemale%3bVALUE%3a2"},
{"field":"AGE","value":"TEXT%3a40%2b-%2b44%3bVALUE%3a6"},
{"field":"STATE","value":"TEXT%3aVIC%3bVALUE%3a2"},
{"field":"END_CHC","value":"TEXT%3aComplete%3bVALUE%3a2"},
{"field":"D2H","value":""},
{"field":"D2V","value":""},
{"field":"PCODE","value":""},
{"field":"PSTATE","value":""},
{"field":"PREGION","value":""},
{"field":"STATEREGION","value":""},
{"field":"TEST1","value":""}]
JSON;
$obj = json_decode($json, true);
foreach($obj as $currTuple)
{
echo $currTuple['field'].':'.urldecode($currTuple['value'])."\n";
}
Also some of the results are url encoded, so you'll probably want to decode that before persisting.

Get Instagram posts count for profile

I'm using PHP to build an application that gets some statistics from individual Instagram accounts.
I do a get request to the following URL to get a JSON formatted string:
https://www.instagram.com/{username}/?__a=1
With json_decode, I get the followers and the followings by:
$follows = $data['user']['follows']['count'];
$followedBy = $data['user']['followed_by']['count'];
But I don't know how to get the posts count.
For example for NASA profile:
https://www.instagram.com/nasa/
... I need the number (currently) 1.967.
Any idea?
And a final question: do I have to use API Key to get the stats, or the GET to the above URL is enough?
what is wrong with
$json = file_get_contents('https://www.instagram.com/nasa/?__a=1');
$obj = json_decode($json);
echo $obj->user->media->count;
it just spit out the correct post count as you wanted?
As of now (2020) Instagram has made some changes to the JSON response and the code below does the same as the accepted answer above, also with formatted output.
$ig = json_decode(file_get_contents('https://www.instagram.com/nasa/?__a=1'));
echo number_format($ig->graphql->user->edge_owner_to_timeline_media->count);

JSON response with objects of the same name - Instagram comments

I have been building a test app that gathers pictures and certain pieces of user information from Instagram (only using PHP). I am not using the official API, but instead parsing the JSON response that I get from the url.
I'm trying to gather comments for a certain post. The issue is that when there's more than one comment, I can see the text for each comment, but the object name in the response is the same (it repeats for every comment): {text}.
Here's an abbreviated example response:
{"text":"I think this is funded by my company","created_at"...,"user":{"username"...}, blah blah blah},
{"text":"Very cool","created_at"...,"user":{"username"...blah blah blah
As you can see, for each comment made, there is a "text" object that I need to grab.
Here is my function (shortened) that parses the JSON and gets the comment text:
function scrape_insta_user_post($postid) {
$insta_source = file_get_contents('https://www.instagram.com/p/'.$postid.'/');
$shards = explode('window._sharedData = ', $insta_source);
$insta_json = explode(';</script>', $shards[1]);
$insta_array = json_decode($insta_json[0], TRUE);
global $the_pic_comments;
$the_pic_comments = $insta_array['entry_data']['PostPage'][0]['media']['comments']['nodes'][0]['text'];
}
I have another function that I use to display $the_pic_comments by simply echoing the results.
echo $the_pic_comments;
In cases where there is more than one {text} object, how would I go about displaying each comment? I'm assuming some kind of foreach() loop might work, but I can't get the foreach() to work with my json_decode() function.
This currently works, but only displays one comment, and everything else is ignored.
Can you help me create a loop that will get each comment from the JSON response?
Thanks!
Judging from your code alone, it seems that it should be:
foreach ($insta_array['entry_data']['PostPage'][0]['media']['comments']['nodes'] as $comment) {
echo $comment['text']; // Or add to array, eg. $comments[] = $comment['text'];
}
Note that since you are not using official API, your mechanism may break any time without notice shall Instagram change anything in their code.

How to echo PHP HashMaps

im new in PHP developing and need your help.
I write a webpage summoner-info.com with the RIOT API.
But im to bad to understand the documentation.
I wana output via echo my states. In the API docs stands:
Return Value: Map[string, List[LeagueDto]]
But i dont understand how to use this.
Doc link: link
I wrote this
$url = "https://{$region}.api.pvp.net/api/lol/{$region}/v2.5/league/by-summoner/{$summoner_ID}?api_key={$api}";
$data = file_get_contents($url);
$data = json_decode($data, true);
print_r($data);
So how can i write something like this
echo $data["tier"["LeagueDto "]]
Assuming this is the kind of response you're expecting (2 summoner ids):
https://github.com/josephyi/taric/blob/master/spec/fixtures/leagues_by_summoner_ids.json
There's no LeagueDto entry in the JSON response. When Riot refers to 'LeagueDto' that's the class that represents the data of the object, but is not meant to be accessed from the response. If you look at the response, you'll have to navigate the JSON. I don't know PHP, but assuming you want summoner id 21066:
$data["21066"] // array of leagues the summoner is in
$data["21066"][0] // first league the summoner is in
$data["21066"][0]["entries"] // array of league entries for the first league
$data["21066"][0]["tier"] // tier of first league
Hope that helps!

Categories