PHP: Get value from array - php

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

Related

How to extract and access data from JSON with PHP when some data changes?

I am trying to bring in some API data to a directory in wordpress.
The data I am trying to get is just crypto coin price, none of the other information but because its format is sort of nested (?) it doesnt seem to work.
{
"bitcoin": {
"usd": 16808.82
}
}
This is my code so far:
<?php
$handle = curl_init();
$url = get_post_meta($entity-\>post()-\>ID, '\_drts_field_004', true);
// Set the url
curl_setopt($handle, CURLOPT_URL, $url);
// Set the result output to be a string.
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($handle);
curl_close($handle);
$data = json_decode($output);
echo $output;
var_dump($data);
The results are:
{
"bitcoin":{
"usd":16833.02
}
}
object(stdClass)#10399 (1) {
["bitcoin"]=> object(stdClass)#10492 (1) {
["usd"]=> float(16833.02)
}
}
In this example I am only after the 16833.02
I am trying to do this for lots of different coins, the "usd" will always be the same but the "bitcoin" will change when other coins.
How can I echo only the number?
I have tried lots of variations of echo but cannot get it? Is it possible to do something like:
echo $data['bitcoin']['usd'];
but rather than bitcoin use * ?
As in anything can be there?
You can access the usd value by decoding the JSON to an array instead of an object like this
$data = json_decode($output, true);
$usd = current($data)['usd'];

PHP: Assign array to variable

i've tried a lot of things to achieve this but none of them seem to
work. Im using PHP 7.4
Let's say i have this:
$othervar = array();
$var = array(1, 2, 3);
$othervar = $var;
THIS doesn't work for me, var_dump($othervar) returns
array(1) { [0]=> string(5) "Array" }
I've tried using array_push, i DON'T WANT to use array_merge because i
need to assign two arrays to one variable. This is what i need to do:
$variable = array();
$variable["type1"] = $data; //Array 1
$variable["type2"] = $otherData; //Array 2
This doesn't work either.
Barmar showed me here that this works so i must be doing it wrong somewhere else.
I'll explan the whole code:
To login to my webpage, i send a request trough AJAX request with jQuery.
function SendData(data, btn, actionOnSuccess, shouldReplace = false, elementToReplace = "", getServerData = true, htmlData = "") {
if (!loading)
{
ToggleLoading();
data.push({name: "action", value: $(btn).data("action")});
data.push({name: "attr", value: JSON.stringify($(btn).data("attr"))});
$.post("SendRequest.php", data)
.done(function (r) {
if (!r.success)
//ajax sent and received but it has an error
else
//ajax sent and it was successfull
})
.fail(function () {
//ajax call failed
});
}
else {
//This determines if some request is already executing or not.
}
}
"action" and "attr" are encrypted values that i send to reference some actions on the system (i'll show more here):
The code goes from AJAX to SendRequest.php where it executes an action let's say, login.
The first lines of SendRequest.php are:
require "Functions.php";
$apiAction = Decrypt($_POST["action"]); //Action
$actionData = json_decode(Decrypt($_POST["attr"])); //Attr
$finalPost = $_POST;
foreach ($actionData as $key => $value) { $finalPost[$key] = $value; }
$finalPost["loggedin_ip"] = $_SERVER['REMOTE_ADDR'];
$result = APICall($apiAction, $finalPost);
Then, this is what i want to achieve to communicate with my API:
function APICall($option, $data = array())
{
session_start();
$post = array("uData" => ArrayToAPI($_SESSION), "uPost" => ArrayToAPI($data));
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_URL, "https://apiurl?" . $option); //option is the ACTION to perform on API (let's say "login") it is an encrypted word on a data-attr atribute on every form/button that creates a communication with API.
$returned = curl_exec($ch);
curl_close ($ch);
$newData = json_decode($returned, true);
return $newData;
}
function ArrayToAPI($array)
{
$toApiData = array();
foreach ($array as $key=>$value) {
if (is_array($value))
$toApiData[$key] = ArrayToAPI($value);
else
$toApiData[$key] = Encrypt($value);
}
return $toApiData;
}
This is what i have on API side:
ob_start();
var_dump($_POST);
$result = ob_get_clean();
$api->EndRequest(false, array("errorDesc" => "a - " . $result));
function EndRequest(bool $task_completed, array $data = array())
{
$jsonData = array();
$jsonData['success'] = $task_completed;
$jsonData['data'] = $data;
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsonData, JSON_FORCE_OBJECT);
exit;
}
This ALWAYS returns
array(2) { ["uData"]=> string(5) "Array" ["uPost"]=> string(5) "Array" }
I hope im more clear now, thanks.
The problem is with the request being sent out from your code because of this line:
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
CURLOPT_POSTFIELDS doesn't support multi-level arrays. Your array values (which the keys are pointing to) are cast to string, which ends up as Array. Use:
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
.. instead to "properly" serialize multidimensional arrays in a post request ("properly" as there are many ways to do just that, but it matches the expected PHP format - with [] to denote arrays).

CURLOPT_POSTFIELDS array of folder content

i'm making a curl post to Google text to speech. I have a set of .flac files, that i want to send to Google Text to Speech service, in order to have the content wrote in a txt file.
This is the code i wrote to do this and it works:
$url = 'https://www.google.com/speech-api/v2/recognize?output=json&lang=it-IT&key=xxx';
$cont2 = array(
'flac/1.flac',
'flac/2.flac',
'flac/3.flac'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: audio/x-flac; rate=44100'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
foreach ($cont2 as $fn) {
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($fn));
$result = curl_exec($ch);
$info = curl_getinfo($ch);
//var_dump($info);
if ($result === false) {
die(curl_error());
}else{
echo "<br />".$fn." upload ok"."<br />";
file_put_contents("pum.txt", $result, FILE_APPEND);
}
}
It works like a charm, in the "pum.txt" i have all the file content wrote and it's ok.
My problem is that i don't want to add to the the array "cont2", each time, the new name o the files i need to pass to, that there are in the "flac folder".
To avoid that, i use "scandir" method, remove "." and ".." string from the array and give that array to the CURL_OPT_POSTFIELD, but the call to GTT return a empty content.
This is the code i wrote to do that (instead $cont2 array)
$directory = 'flac/';
$cont = array_diff(scandir($directory), array('..', '.', '.DS_Store'));
Print_r of that is the same as $cont2 array:
array(3) {
[3]=>
string(6) "1.flac"
[4]=>
string(6) "2.flac"
[5]=>
string(6) "3.flac"
}
But Google TTS return empty result.
Does anyone please tell me where i'm making mistake?
Kind Regards
Brus
EDIT: use "$cont = glob("$directory/*.flac");" solved the issue. Hope help some others.
scandir() won't include full path information - it'll only return filenames. SO when you're building your array of filenames to loop on and send to google, you'll have to include that directories yourself.
e.g.
$dir = 'flac';
$files = scandir($dir);
foreach($files as $key => $file);
$files[$key] = $dir . '/' . $file;
}
e.g. scan dir will return file1.flac, but you need to have flac/file1.flac. Since you're not including the path information, you're trying to do file_get_contents() on a filename which doesn't exist, and are sending a boolean false (file_get failed) over to google.
As Marc B states you need the directory to the files which is missing. I would just use glob as it will return exactly what you need:
$cont = glob("$directory/*.flac");

JSON to PHP Output

I usually manage to figure stuff out by myself, but on this occasion I've had to register an account and ask for help before I jump out the window.
I'm trying to output some basic JSON data to php, all I need to do is echo it out, the rest I'll figure out.
The API gives this guide:
{
"success" : true,
"message" : "",
"result" : {
"Bid" : 2.05670368,
"Ask" : 3.35579531,
"Last" : 3.35579531
}
}
An example of the URL I'll be using: https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC
All I want to output is the 'Last' data, I don't care about the rest, keeping the decimal in the right place is also important.
I've tried all sorts, I can't get it to output it properly :(. I've ran a var_dump which spits out:
array(3) { ["success"]=> bool(true) ["message"]=> string(0) "" ["result"]=> array(3) { ["Bid"]=> float(0.00011505) ["Ask"]=> float(0.000116) ["Last"]=> float(0.00011505) } }
If someone could just tell me the few lines of code to put the 'Last' number into a variable called $lastBid I will love you long time!
Thanks guys!
use json_decode - php method to decode json
http://php.net/manual/en/function.json-decode.php
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
Here you have an example,
$contents = file_get_contents("https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC");
$json = json_decode($contents);
$lastBid = $json->result->Last;
$lastBid would then be set to 0.01189802
You need to json_decode() the result.
that kind of data is called json. php permits you to convert that json (which is a string) to a php array.
to get it, you need to convert it and then access to the value you'd like using array rules.
// save in a variable the data you're going to process
$json = '{
"success" : true,
"message" : "",
"result" : {
"Bid" : 2.05670368,
"Ask" : 3.35579531,
"Last" : 3.35579531
}
}';
// json_decode is a function that allows you to obtain an array
// (the second parameter set to true indicates that the array'll be an associative one)
$data = json_decode($json, TRUE);
/*
every php array has an internal pointer which points to a position in the array.
the end pointer, if not moved, points to the last position. to access to the value
you want, first get the last value (an array called "result"),
then access to the last value of that array (called "last").
the property you'll get is the float value you requested!
*/
var_dump(
end(
end($data)
)
);
and here, there is the output:
float(3.35579531)
Access it by:
$url = 'https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC';
$data = file_get_contents($url);
$data = json_decode($data);
$last = $data->result->Last;
If you like using arrays instead of object orrientation style, json_decode has an extra boolean param, that converts it too an array if you feel more comfortable using that.
$url = 'https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC';
$data = file_get_contents($url);
$data = json_decode($data,true);
$last = $data['result']['Last'];
Side note; For accessing API's I would rather advice you to use curl instead of file_get_contents. It gives you better control, for instance with timeouts. But you have many more options. You can use this function;
function curl($URL,&$errmsg){
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_URL, $URL);
curl_setopt($c, CURLOPT_TIMEOUT, 10);
$contents = curl_exec($c);
if (curl_errno($c)){
$errmsg = 'Failed loading content.';
curl_close($c);
return;
}
else{
curl_close($c);
return($contents);
}
}
And your code then would be:
$url = 'https://bittrex.com/api/v1.1/public/getticker?market=BTC-LTC';
$data = curl($url, $errmsg);
$data = json_decode($data,true);
$last = $data['result']['Last'];

curl response cannot be handled after saved in a variable PHP

$ch = curl_init("http://acrs.bboxpr.com/getAddress.php?lat=35.545112&lng=-90.657635");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$address = curl_exec($ch);
curl_close($ch);
//prints the address
echo $address;
//$token = strtok($address, ",");
//$phaddress=array();
//while ($token != null)
//{
//array_push($phaddress,$token);
//$token = strtok(",");
//}
//print_r($phaddress); //blank
In the line echo $address; will print in the content in the page, but if I uncomment the code below(the one that starts with: $token=strtok),$address will look empty. I added more code that uses the results with $address (but I did not include that in here) and sometimes appears the source-code of the site that is invoked in the curl initialization. So I think maybe curl is taking a little bit longer, but I tried to put a sleep before srtok, but didn't work.
In your while loop, you have to replace $token = strtok(","); with $token = strtok($address, ",");
Since you are tying to get MAP information from google i think you are using the wrong approch my using javascript because that might be more difficult to parse
Why don't you try using PHP directly
$ch = curl_init("http://maps.google.com/maps/api/geocode/json?latlng=35.545112,-90.657635&sensor=false");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$return = curl_exec($ch);
curl_close($ch);
$geoOutput = json_decode($return,true);
echo "<pre>" ;
foreach($geoOutput as $key => $data)
{
if(is_array($data))
{
foreach($data as $cKey => $cData)
{
var_dump($cData['formatted_address']);
}
}
}
Output
string(43) "6724-6916 Bay Ln, Harrisburg, AR 72432, USA"
string(16) "Bolivar, AR, USA"
string(25) "Harrisburg, AR 72432, USA"
string(17) "Poinsett, AR, USA"
string(13) "Arkansas, USA"
Change your while loop to this: while ($token !== false)

Categories