I'm using this little PHP function that I wrote to make calls to my master database:
$db_request = curl_init(DB_ROOT.'/action/register.php');
curl_setopt($db_request, CURLOPT_HEADER, 0);
curl_setopt($db_request, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($db_request, CURLOPT_POSTFIELDS, http_build_query($variables));
$db_response = curl_exec($db_request);
curl_close ($db_request);
parse_str($db_response, $information);
On register.php I use the following to respond:
echo http_build_query(array(
'test1'=>'value1',
'test2'=>'value2',
'test3'=>'value3'
));
My problem comes when trying to retrieve the first index of any given response. I can use var_dump($information) and will receive array(3) { ["test1"]=> string(6) "value1" ["test2"]=> string(6) "value2" ["test3"]=> string(6) "value3" }. However, when I try to echo $information['test1'], I receive this: Notice: Undefined index: test1 in....
Echoing anything other than the first index doesn't give me this problem.
Does anyone have any thoughts?
parse_str return type is void
Update your code
parse_str($db_response, $information);
Related
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 2 years ago.
This is the first time I have used curl, and am confused how exactly the $response is formatted, and how I go about accessing the information I want in it. I am trying to access a particular variable from a curl response in PHP to be used in a future conditional. I was provided the URL, and headers to use as an API endpoint, and thus can't change anything on that end. Here is the code for the curl response :
$ch = curl_init();
$url = "https://thewebsitesurl.com";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'x-branch: 21',
'x-branchhash: fijef89ivjw8934y8f9fifk920a',
'accept: application/json'
));
$response = curl_exec($ch);`
The contents of a var_dump($response) yields :
string(187) "{"code":"5122","time":"1589812650","voucher":{"code":"5122","comments":"","amount":"11.00","balance":"11.00","created":"1589609333","expiry":"1652616000","redeemed":false,"voided":false}}"
I need to access the "redeemed" and "voided" field. Of course this being a big long string means I can't do that (I believe). Is there a CURLOPT I should be setting so the response isn't received as one big string?
Further if I decode it with $data = var_dump(json_decode($result, true)); the contents are :
array(3) { ["code"]=> string(4) "5122" ["time"]=> string(10) "1589814039" ["voucher"]=> array(8) { ["code"]=> string(4) "5122" ["comments"]=> string(0) "" ["amount"]=> string(5) "11.00" ["balance"]=> string(5) "11.00" ["created"]=> string(10) "1589609333" ["expiry"]=> string(10) "1652616000" ["redeemed"]=> bool(false) ["voided"]=> bool(false) } }
To me this seems much more workable than a long string. However I am struggling to access the ["expiry"], ["redeemed'], and ["voided"] variables. In fact I am struggling just to access the ["code"] string "5122" I have tried :
echo $data[0]['code'];
echo $data[0]["code"];
echo $data['code'];
echo $data["code"];
All 4 of those echos are blank. I have tried to remove "curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);" as well. Afterwards var_dump($result); looks like :
{"code":"5122","time":"1589815247","voucher":{"code":"5122","comments":"","amount":"11.00","balance":"11.00","created":"1589609333","expiry":"1652616000","redeemed":false,"voided":false}}bool(true)
I am probably misunderstanding something basic here. But any help would be appreciated on how I could access the values in ["expiry"], ["redeemed'], and ["voided"]. Thank you for your assistance.
$data = json_decode($result, true);
This will return an array
$data = json_decode($result);
This will return an object.
Do not use var_dump inside this because it is a parse function, just for dumping data. So the final should be:
$data = json_decode($result, true);
$code = $data['code']; // " or ' are not different in this case
I was trying to parse the json data from a url using cURL and then json_decode to access the objects but I failed. I already search it how to access but I failed.
this is the links that I visited hoping that I can solve the problem.
http://www.dyn-web.com/tutorials/php-js/json/decode.php
https://stackoverflow.com/questions/12429029/php-get-values-from-json-encode
https://stackoverflow.com/questions/20193575/fetch-json-data-using-php
https://stackoverflow.com/questions/12429029/php-get-values-from-json-encode
https://stackoverflow.com/questions/4433951/decoding-json-after-sending-using-php-curl
this is the result of the var_dump($obj);
array(1) {
["login"]=>
array(2) {
["error"]=>
bool(false)
["user"]=>
array(5) {
["br_code"]=>
int(0)
["mem_id"]=>
int(202)
["username"]=>
string(8) "johndoe"
["email"]=>
string(33) "johndoe#gmail.com"
["created_at"]=>
string(19) "2017-08-07 15:35:39"
}
}
}
and this is my PHP code
<?php
session_start();
$ch = curl_init('http://localhost/sample/login.php');
$username= $_SESSION["USERNAME"];
$password= $_SESSION["PASSWORD"];
$credentials = [
'username' => $username,
'password' => $password
];
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $credentials);
curl_setopt($ch, CURLOPT_USERNAME, "{$username}:{$password}");
// execute!
$response = curl_exec($ch);
// close the connection
curl_close($ch);
$obj= json_decode($response, true);
// echo $obj; // Notice: Array to string conversion in
// echo $obj[0]; // Undefined offset
// echo $obj->user; //Trying to get property of non-object in
var_dump($obj);
?>
seems an array of array so
eg: for username
var_dump($obj['login']['user']['username']);
and so on for others values
$my_username = $obj['login']['user']['username']);
Your data is in login array so try following to get details of user
$user = $obj['login']['user'];
//to print email
echo $user['email'];
//to print username
echo $user['username'];
//so on
When you do json_decode($response, true), and you are using second parameter as true, it will decode it into associative array.
Your var_dump also says that it is array. So, you need to access $obj as array not object
if you want to access the user array:
$obj['login']['user']
if you want to access the username/br_code:
$obj['login']['user']['username'];
$obj['login']['user']['br_code'];
more info about json_decode
json_decode decodes a JSON string into a multi dimensional array
you get that error because in PHP objects are not arrays
just access with [] and you are fine
$obj['user']['field_requested']
I am trying to integrate the API of a game via cURL, I tried with the code that you see below, however, gives me error
Notice: Trying to get property of non-object in
C:\xampp\htdocs\over\index.php on line 173
JSON is not "data" and I think that's what bothers me:
{"SoloKills": "494", "DamageDone": "758,071", "Eliminations": "1,911",}
$mode = "quick-play";
$allheroes = curl_init();
curl_setopt($allheroes, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($allheroes, CURLOPT_RETURNTRANSFER, true);
curl_setopt($allheroes, CURLOPT_FAILONERROR, true);
curl_setopt($allheroes, CURLOPT_URL,"https://api.lootbox.eu/{$platform}/{$country}/{$battletag}/quick-play/allHeroes/");
$result3 = curl_exec($allheroes);
curl_close($allheroes);
$stats3 = json_decode($result3, true);
foreach ($stats3 as $allhero)
{
$uccisioni = $allhero['Eliminations'];
echo $uccisioni;
}
You have to becarefull in encoding. It's affect to whole your codes
"DamageDone": "758,071" not
DamageDone": "758,071"
you've forgot Quote Marks!
You don't have key "ObjectiveKills" at this JSON
{"SoloKills": "494", "DamageDone": "758,071", "Eliminations": "1,911"}
But i think you can get "SoloKills", "DamageDone", "Eliminations" like:
foreach ($stats3 as $allhero) {
$uccisioni = $allhero['SoloKills'];
echo $uccisioni;
}
Update:
You don't need foreach here, I got
array(41) { ["SoloKills"]=> string(2) "55" ["ObjectiveKills"]=> string(3) "138" ...]}
You can get $stats3['Eliminations']
I'd like to display the number of likes for my Facebook page on my website. The previous method I used isn't working anymore since a couple of days.
When I call the Facebook graph API like this:
https://api.facebook.com/method/links.getStats?urls=http://www.facebook.com/549585444&format=json
It gives me the following output (fictional example):
[{"url":"http:\/\/www.facebook.com\/549585444","normalized_url":"http:\/\/www.facebook.com\/549585444","share_count":0,"like_count":122,"comment_count":0,"total_count":122,"click_count":0,"comments_fbid":null,"commentsbox_count":0}]
Now I like to echo the like count:
<?php
$fb_page = "549585444";
$url = "https://api.facebook.com/method/links.getStats?urls=http://www.facebook.com/".$fb_page."&format=json";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$json_returned = curl_exec($curl);
curl_close($curl);
$json_returned = json_decode($json_returned, true);
echo $json_returned['like_count'];
?>
But the number doesn't appear. Any idea why?
As you can see in the JSON output, the answer is wrapped in an array:
array(1) {
[0]=>
array(9) {
["url"]=>
string(33) "http://www.facebook.com/549585444"
["normalized_url"]=>
string(33) "http://www.facebook.com/549585444"
["share_count"]=>
int(0)
["like_count"]=>
int(0)
["comment_count"]=>
int(0)
["total_count"]=>
int(0)
["click_count"]=>
int(0)
["comments_fbid"]=>
NULL
["commentsbox_count"]=>
int(0)
}
}
To get the number output, you'll have to get the first item in the array by changing this row:
echo $json_returned['like_count'];
To this:
echo $json_returned[0]['like_count'];
I am using the bukkit JSONAPI and php JSONAPI.php to get the list of players on my minecraft server to my website. To get the count, I do this:
require('JSONAPI.php'); // get this file at: https://github.com/alecgorge/jsonapi/raw/master/sdk/php/JSONAPI.php
$api = new JSONAPI("localhost", 20059, "user", "pass", "salt");
$limit = $api->call("getPlayerLimit");
$count = $api->call("getPlayerCount");
$c = curl_init($url);
curl_setopt($c, CURLOPT_PORT, 20059);
curl_setopt($c, CURLOPT_HEADER, false);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_TIMEOUT, 10);
$result = curl_exec($c);
curl_close($c);
echo "<h5>Players online:</h5>";
$num= '' . $count['success'] . '/' . $limit['success'];
echo $num;
This returns: 1/40
Then, I try to get the player list:
$list = $api->call('getPlayerNames');
echo $list;
This just returns: Array
However, when I do
var_dump($api->call('getPlayerNames'));
I get:
array(3) { ["result"]=> string(7) "success" ["source"]=> string(14) "getPlayerNames" ["success"]=> array(1) { [0]=> string(8) "gauso001" } }
However, what I want is simply a list of the players without all of the extra stuff. Sorry if this is a noob question, I only know pretty basic PHP.
Stuff that might help:
method docs: http://alecgorge.com/minecraft/jsonapi/apidocs/#package-JSONAPI%20standard
tell me what else..
THANK YOU in advance, I hope I'll be as good as you in PHP one day :D
Looks like player names, oddly enough, are contained as an array in the success key.
To access the player names, you could:
$list = $api->call('getPlayerNames');
// debug
print_r($list['success']);
// direct access
echo $list['success'][0];
// loop
foreach($list['success'] as $player) {
echo $player;
}
Format to your needs. But that should get you started.
Note: I'd also encourage you to learn about Arrays in PHP.
$api->call('getPlayerNames') returns a named array, one key of which (success) is another array containing the player names. Iterate over the success key to get the player list.
$players = $api->call('getPlayerNames');
foreach($players['success'] as $player) {
echo $player;
}