XBox PHP API Call - php

Here is a link to the demo: http://davidwalsh.name/xbox-api
I created a php file with the following content..
<?php
// Settings
$gamertag = 'RyanFabbro';
$profileUrl = 'http://www.xboxleaders.com/api/profile/'.$gamertag.'.json';
// Get information about me
$info = file_get_contents($profileUrl);
// To JSON
$json = json_decode($info);
$user = $json->user;
?>
Here is what its supposed to look like when i load the file (except with my gamertag data)
{
"status": {
"is_valid": "yes",
"is_cheater": "no",
"tier": "gold"
},
"profile": {
"gamertag": "dwalsh83",
"gamerscore": 300,
"reputation": 20,
"gender": "male",
"motto": "Watch your head.",
"name": "David Walsh",
"location": "Madison, WI, US",
"bio": "There is, and only can be, Call of Duty.",
"url": "http:\/\/live.xbox.com\/en-US\/Profile?gamertag=dwalsh83",
"avatar_tile": "http:\/\/image.xboxlive.com\/global\/t.fffe07d1\/tile\/0\/2000b",
"avatar_small": "http:\/\/avatar.xboxlive.com\/avatar\/dwalsh83\/avatarpic-s.png",
"avatar_large": "http:\/\/avatar.xboxlive.com\/avatar\/dwalsh83\/avatarpic-l.png",
"avatar_body": "http:\/\/avatar.xboxlive.com\/avatar\/dwalsh83\/avatar-body.png",
"launch_team_xbl": "no",
"launch_team_nxe": "no",
"launch_team_kin": "no"
}
}
But it is not displaying anything, what am i doing wrong?
When I go to http://www.xboxleaders.com/api/profile/ryanfabbro.json, it displays fine.
Uodate*
i tryd doing this in a php file
<?php
// Settings
$gamertag = 'RyanFabbro';
$profileUrl = 'http://www.xboxleaders.com/api/profile/'.$gamertag.'.json';
// Get information about me
$info = file_get_contents($profileUrl);
// To JSON
$json = json_decode($info);
$user = $json->user;
$user = $json->profile;
$user = $json->data;
$profile = $json->data;
?>
<img src="<?php echo $profile->avatar_body; ?>" alt="<?php echo $profile->gamertag; ?>" class="avatar" />
this resulted in the page still being blank so when i viewed the source all it returned was
<img src="" alt="" class="avatar" />
update 2 #ae14 & 2g
i also tried (all in 1 php file)
<?php
// Settings
$gamertag = 'RyanFabbro';
$profileUrl = 'http://www.xboxleaders.com/api/profile/'.$gamertag.'.json';
// Get information about me
$info = file_get_contents($profileUrl);
// To JSON
$json = json_decode($info);
$user = $json->data;
?>
<?php echo $user->name ?>
which still resulted in a blank page, is that what you were meaning i should do? i also tried this same way with 2g suggestion to no avail

It looks like you need to use
$user = $json->Data
to get the user information

This is my PHP file :
<?php
// Settings
$gamertag = urlencode('yourgamertagwithspaceetcetc..');
$profileUrl = 'http://www.xboxleaders.com/api/profile/'.$gamertag;
// Get information about me
$info = file_get_contents($profileUrl);
echo $info;
// To JSON
$json = json_decode($info);
$user = $json->Data;
echo $user->Gamertag;
?>
I've to use urlEncode beacause my gamertag had a spaces inside. I suggest you to test the final url on the browser before start the php file.
For test use $user->Gamertag because Name's property it's always blank.. I don't know why.
This is JSON Data returned from the service
"Data": {
"Tier": "gold",
"IsValid": 1,
"IsCheater": 0,
"IsOnline": 0,
"OnlineStatus": "Last seen 11\/10\/2012 playing Modern Warfare® 3",
"XBLLaunchTeam": 0,
"NXELaunchTeam": 0,
"KinectLaunchTeam": 0,
"AvatarTile": "https:\/\/avatar-ssl.xboxlive.com\/avatar\/xxxxxxxx\/avatarpic-l.png",
"AvatarSmall": "http:\/\/avatar.xboxlive.com\/avatar\/xxxxxx\/avatarpic-s.png",
"AvatarLarge": "http:\/\/avatar.xboxlive.com\/avatar\/xxxxxx\/avatarpic-l.png",
"AvatarBody": "http:\/\/avatar.xboxlive.com\/avatar\/xxxxxxx\/avatar-body.png",
"Gamertag": "xxxxxxxxxxxxxxxxx",
"GamerScore": 4165,
"Reputation": 20,
"Name": "",
"Motto": "",
"Location": "",
"Bio": ""
},
"Stat": "ok",
"In": 2.273,
"Authed": "false",
"AuthedAs": null
You can access using the same method for the Gamertag... simpy call
$user->AvatarSmall
I don't had php installed on my machine so first I've downloaded the PHP 5.4.8 for Windows and I've used the Built-in web server of this release Here more info.
Hope can help you

Related

PHP fails to parse JSON - Unexpected Integer

I'm trying to make an application that will use a JSON input. Below is some code that shows the problem when run. The problem being a syntax error; unexpected integer from the "etag" line ("$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",). When I remove the etag line it runs fine but otherwise I get an error. Can I remove the etag line (not needed anyway) before being parsed or get around it some other way? I unfortunately cant change what the API sends.
<?php
$json = '{
"Form": {
"Id": "1",
"InternalName": "SignUp",
"Name": "Sign Up"
},
"$version": 7,
"$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",
"Email": "test#email.com",
"Phone": "(123) 412-3412",
"CarrierServiceProvider": "Sprint",
"WTSKeywords": "Testing WTS",
"WTBKeywords": "Testing WTB",
"Id": "1-3",
"Email_IsRequired": false,
"Phone_IsRequired": false,
"CarrierServiceProvider_IsRequired": true
}';
$data = json_decode($json);
echo $data->Email;
echo "\n";
echo $data->WTBKeywords;
?>
Code should output: test#email.com Testing WTB
You json string has both ' and ", so you cannot simple use single or double quoted.
Use heredoc like this,
$json = <<<EOT
{
"Form": {
"Id": "1",
"InternalName": "SignUp",
"Name": "Sign Up"
},
"$version": 7,
"$etag": "W/\"datetime'2019-10-31T23%3A22%3A09.7835369Z'\"",
"Email": "test#email.com",
"Phone": "(123) 412-3412",
"CarrierServiceProvider": "Sprint",
"WTSKeywords": "Testing WTS",
"WTBKeywords": "Testing WTB",
"Id": "1-3",
"Email_IsRequired": false,
"Phone_IsRequired": false,
"CarrierServiceProvider_IsRequired": true
}
EOT;
$data = json_decode($json);
echo $data->Email;
echo "\n";
echo $data->WTBKeywords;

What is the correct way to insert array into a file using PHP?

I'm trying to put a users "favourite" game into the corresponding file for their user upon post.
if(isset($_POST['favourite'])){
$filetxt = 'data/users.json';
$formdata = $_POST['favourite']; //this contains the value "game"
$arr_data = array();
if(file_exists($filetxt)) {
$jsondata = file_get_contents($filetxt);
$arr_data = json_decode($jsondata, true);
}
$arr_data[][$_SESSION['username']]['favourite'] = $formdata;
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents('data/users.json', $jsondata);
}
The file is structured as:
[
{
"CNR": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "test",
"password": "test",
"favourite": []
}
},
{
"usertest": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "United States",
"password": "password",
"favourite": []
}
}
]
Currently it will add the correct data however not into the array, but onto the end.
[
{
"CNR": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "test",
"password": "test",
"favourite": []
}
},
{
"usertest": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "United States",
"password": "password",
"favourite": []
}
},
{
"CNR": {
"favourite": "game"
}
}
]
I've tried things like arraypush, splice and other methods however I'm not sure what is the best for this use case.
Any thoughts/recommendations on how I can best achieve this with the desired result are greatly appreciated, thanks!
$arr_data[$_SESSION['username']]['favourite'][] = $formdata;
Difference is that I moved [] to the end of the $arr_data.
Before adding it to array, you need to check if the key exists and then proceed rather than just adding the code.
if(isset($_POST['favourite'])){
$filetxt = 'data/users.json';
$formdata = $_POST['favourite']; //this contains the value "game"
$arr_data = array();
if(file_exists($filetxt)) {
$jsondata = file_get_contents($filetxt);
$arr_data = json_decode($jsondata, true);
}
// changes over here
if(isset($arr_data[$_SESSION['username']])){
if(isset($arr_data[$_SESSION['username']]['favourite'])){
$arr_data[$_SESSION['username']]['favourite'][] = $formdata;
} else {
$arr_data[$_SESSION['username']]['favourite'] = $formdata;
}
} else {
$arr_data[][$_SESSION['username']]['favourite'] = $formdata;
}
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents('data/users.json', $jsondata);
}
I can see that most have answered the question but might I also provide some suggestions (food for thought) on your process?
1). Firstly, I can't work out if you are storing ALL users in a single file or if there's a file per user. Example username.json
I am going to assume there is a file per username because there should be to make file writes quicker and it would require the main file to be locked for everyone else just because one user is writing to it.
2). I noticed that the favourite part seems to be stored in the _SESSION too. If the _SESSION is storing the same mini array in it (a replica of what is stored in the file) then there's no point in opening the file to write a single value and then save it again. You may as well just write over the existing file straight away. Like this...
$writeToFile = json_encode($_SESSION[mydata]);
$fh = fopen("/path/to/username.json","w+");
fwrite($fh,$writeToFile);
fclose($fh);
// You could also use file_put_contents but most prefer
// to use fopen()
3). I will assume the passwords you are storing are encrypted and nobody can type [yourdomain]/users/username.json to see the raw output of the json files. You might want to ensure .json files aren't accessible from the browser. You can do that with .htaccess.
Problem is in this code, you are creating every time a new sub array:
Change this:
$arr_data[][$_SESSION['username']]['favourite'] = $formdata;
To this
if(isset($arr_data[$_SESSION['username']])) {
$arr_data[$_SESSION['username']]['favourite'] = $formdata;
}

Facebook like count url

As Facebook changed their API and deprecated the old one, I need to get data (likes count, share count, comment count) about single pages.
I figured out how to get data over Facebook graph (example link):
https://graph.facebook.com/?fields=og_object{likes.limit(0).summary(true)},share&ids=http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9
But now I don't know how to echo single data (likes count) in php. I tried with json, but had no sucsess:
$json = file_get_contents($xml);
$json_output = json_decode($json);
Any suggestions how to make this work?
The API Explorer adds the Access Token automatically, but you have to add it manually in your URL:
https://graph.facebook.com/?fields=og_object{likes.limit(0).summary(true)},share&ids=http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9&access_token=xxx
Result:
{
"http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9": {
"og_object": {
"likes": {
"data": [
],
"summary": {
"total_count": 0,
"can_like": true,
"has_liked": false
}
},
"id": "949055545223224"
},
"share": {
"comment_count": 0,
"share_count": 346
},
"id": "http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9"
}
}
The results of json_decode() are Objects.
So you can easily browse through like this:
<?php
$url = 'https://graph.facebook.com/?fields=og_object{likes.limit(0).summary(true)},share&ids=http://www.businessinsider.com/airlines-dont-disclose-carrier-fee-that-inflates-ticket-prices-2016-9';
$json = file_get_contents($url);
$json_output = json_decode($json);
foreach( $json_output as $site=>$data ){
echo $site."\n";
echo $data->og_object->likes->summary->total_count;
}
?>

how to grab the json returned value in php?

I have a script in my facebook application which will provide the user with the list of his Facebook friends in a dropdown list. With the code below, I am able to grab the user's friends, but I am only getting the User ID.
$api_key = 'xxx';
$secret = 'xxx';
include_once 'facebook.php';
$facebook = new Facebook($api_key, $secret);
$friends = $facebook->api_client->friends_get();
foreach ($friends as $friend)
{
echo $friend;// returns only the friend's ID and not name but i want to show the name
$url="https://graph.facebook.com/".$friend."/";
$res=file_get_contents($url);
}
With this link I want to grab the user's name and display it on a dropdown list. How can I grab it and echo only the name from $url?
{
"id": "4",
"name": "Mark Zuckerberg",
"first_name": "Mark",
"last_name": "Zuckerberg",
"link": "http://www.facebook.com/zuck",
"gender": "male",
"locale": "en_US"
}
Take a look at JSON_decode
http://www.php.net/manual/en/function.json-decode.php
From the PHP manual:
$var = json_decode ( $result );
and echo what you want, like: echo $var ['link'];
$data = json_decode($str);
echo $data['name'];
simple as that

Parsing JSON object in PHP using json_decode

I tried to request the weather from a web service supplying data in JSON format. My PHP request code, which did not succeed was:
$url="http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
echo $data[0]->weather->weatherIconUrl[0]->value;
This is some of the data that was returned. Some of the details have been truncated for brevity, but object integrity is retained:
{ "data":
{ "current_condition":
[ { "cloudcover": "31",
... } ],
"request":
[ { "query": "Schruns, Austria",
"type": "City" } ],
"weather":
[ { "date": "2010-10-27",
"precipMM": "0.0",
"tempMaxC": "3",
"tempMaxF": "38",
"tempMinC": "-13",
"tempMinF": "9",
"weatherCode": "113",
"weatherDesc": [ {"value": "Sunny" } ],
"weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
"winddir16Point": "N",
"winddirDegree": "356",
"winddirection": "N",
"windspeedKmph": "5",
"windspeedMiles": "3" },
{ "date": "2010-10-28",
... },
... ]
}
}
}
This appears to work:
$url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710%22';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['data']['weather'] as $item) {
print $item['date'];
print ' - ';
print $item['weatherDesc'][0]['value'];
print ' - ';
print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />';
print '<br>';
}
If you set the second parameter of json_decode to true, you get an array, so you cant use the -> syntax. I would also suggest you install the JSONview Firefox extension, so you can view generated json documents in a nice formatted tree view similiar to how Firefox displays XML structures. This makes things a lot easier.
If you use the following instead:
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
The TRUE returns an array instead of an object.
Try this example
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
http://php.net/manual/en/function.json-decode.php
NB - two negatives makes a positive . :)
Seems like you forgot the ["value"] or ->value:
echo $data[0]->weather->weatherIconUrl[0]->value;
When you json decode , force it to return an array instead of object.
$data = json_decode($json, TRUE); -> // TRUE
This will return an array and you can access the values by giving the keys.
You have to make sure first that your server allow remote connection so that the function file_get_contents($url) works fine , most server disable this feature for security reason.
While editing the code (because mild OCD), I noticed that weather is also a list. You should probably consider something like
echo $data[0]->weather[0]->weatherIconUrl[0]->value;
to make sure you are using the weatherIconUrl for the correct date instance.

Categories