Facebook like count url - php

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;
}
?>

Related

How to put an API return string into an array

I have a string that i get from an API and i wish i could put it in a array so i could check the values that came from the return.
String return example:
{
"code":"000",
"message":"XXX",
"date":"2018-05-17",
"hour":"09:16:09",
"revision":"",
"server":"XX",
"content":{
"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}
}
}
What I need:
echo $string['code'];
Javascript has no problem with JSON encode command. But how can I do it with PHP?
First of all your JSON data seems to be invalid (Some brackets missing). It needs to be like this:-
{
"code": "000",
"message": "XXX",
"date": "2018-05-17",
"hour": "09:16:09",
"revision": "",
"server": "XX",
"content": {
"nome": {
"info": "SIM",
"conteudo": [{
"field1": "XXXX",
"field2": "XX"
}]
}
}
}
Now You need to decode this JSON data and then get data based on the index
$array = json_decode($json,true);
echo $array['code'];
Output:-https://eval.in/1005949
You can decode the JSON string to Array in PHP.
$str = '{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}';
$decodedValue = json_decode($str, true);
var_dump($decodedValue);
Your example string is not valid json, you are missing some closing brackets.
This should be the correct way:
'{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}}}'
As for your question. in PHP you can easily use json_decode
Example:
<?php
$json = '{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}}}';
$decoded_json = json_decode($json, true);
echo $decoded_json['code'];
You can see it working here

How do I get the ErrorCode variable value from the response variable after message sending using CURL?

After executing CURL I am getting the $result variable value as:
{
"ErrorCode": "000",
"ErrorMessage": "Success",
"JobId": "6878b812-766d-48a2-9dae-2b0edf2d84d4",
"MessageData": [{
"Number": "919730842844",
"MessageParts": [{
"MsgId": "919730842844-64a40d7611f94c03bea1045fdfa9bac5",
"PartId": 1,
"Text": "\u0027messagecontentsmstest\u0027"
}]
}]
}
Now i need to check for the ErrorCode == 000, so how can I get the value of individually ErrorCode?
This response received is like JSON.
So I thought to decode it as an json_decode:
$chk = json_decode($result);
echo $chk->ErrorCode;
or we can even try in another way like,
$array = json_decode($result, true);
echo $array['ErrorCode'];

XBox PHP API Call

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

decoding stripe json with json_decode not working

I have json from stripe and I am trying to decode it json_decode.
I am not getting an error. Just nothing is returning. I am getting the data back from stripe, I just cant decode it.
{
"created":1326853478,
"data":{
"object":{
"amount":4500,
"card":{
"country":"US",
"cvc_check":"pass",
"exp_month":7,
"exp_year":2014,
"fingerprint":"9aQtfsI8a17zjEZd",
"id":"cc_00000000000000",
"last4":"9782",
"object":"card",
"type":"Visa"
},
"created":1322700852,
"currency":"usd",
"disputed":false,
"fee":0,
"id":"ch_00000000000000",
"livemode":false,
"object":"charge",
"paid":true,
"refunded":true
}
},
"id":"evt_00000000000000",
"livemode":false,
"type":"charge.refunded"
}
// retrieve the request's body and parse it as JSON
$body = #file_get_contents('php://input');
$event_json = json_decode($body,true);
print_r($event_json);
Any ideas?
The php://input stream allows you to read raw data from the request body. This data will be a string and depending on what sort of values are in the request, will look something like:
"name=ok&submit=submit"
This is not JSON and therefore won't decode as JSON the way you expect.The json_decode() function returns null if it can't be decoded.
Where are you getting the JSON you posted above? That is the value you need to pass into json_decode().
If JSON is being passed in the request, like in the instance of callbacks, you would still need to parse that portion out to get just the JSON. If the php://input stream gives you name=ok&submit=submit&json={"created": 1326853478} then you'd have to parse it out. You can use this function from the PHP manual to seperate the values to work like the $_POST array:
<?php
// Function to fix up PHP's messing up POST input containing dots, etc.
function getRealPOST() {
$pairs = explode("&", file_get_contents("php://input"));
$vars = array();
foreach ($pairs as $pair) {
$nv = explode("=", $pair);
$name = urldecode($nv[0]);
$value = urldecode($nv[1]);
$vars[$name] = $value;
}
return $vars;
}
?>
To use it:
$post = getRealPOST();
$stripe_json = $post['json'];
$event_json = json_decode($stripe_json);
Here, I ran this:
<?php
$data = '{ "created": 1326853478, "data": { "object": { "amount": 4500, "card": { "country": "US", "cvc_check": "pass", "exp_month": 7, "exp_year": 2014, "fingerprint": "9aQtfsI8a17zjEZd", "id": "cc_00000000000000", "last4": "9782", "object": "card", "type": "Visa" }, "created": 1322700852, "currency": "usd", "disputed": false, "fee": 0, "id": "ch_00000000000000", "livemode": false, "object": "charge", "paid": true, "refunded": true } }, "id": "evt_00000000000000", "livemode": false, "type": "charge.refunded" }';
$arr = json_decode($data, true);
print_r($arr);
?>
And it worked. So, theoretically you should be able to use:
<?php
$arr = json_decode(file_get_contents('php://input'), true);
print_r($arr);
?>
As Ignacio Vazquez-Abrams said, don't use the '#' character because it obscures error messages and makes it harder to debug.
I would also check what version of PHP you have. json_decode() is only available on version 5.2.0 and later.

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