JSON to PHP Output - php

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'];

Related

Pull JSON API results from URL and display in PHP

I've been trying to do this for a couple of days through trial and error etc, but getting absolutely nowhere. PHP isn't my strong point, but I'm generally comfortable with it that I can learn as I go when I need to do specific things.
What I'm trying to do, is take the API from one platform that is used, and input it into another platform that is used. I can get the data from the API easily enough via a URL, and it runs fine on a different server so I'm pretty sure everything is fine on that side of things.
The issue is, that when I do manage to get it from a URL, it comes out looking quite messy. Nothing I've tried so far will display it as a nice tidy block. Furthermore, I'd like to be able to pull specific data from the result and display just that. The data comes out as follows when visited via the URL (have changed values for privacy etc, but the integrity should remain):
{"Data":[{"DeviceID":"1","DeviceName":"Phone 1","Platform":"Phone OS","Edition":"Deluxe","State":"0","Time":"2016-03-16T13:47:44+01:00"}]}
Essentially, what I'm trying to do is:
Display the data in a block list, as opposed to long lines
Allow selection of a specific device through "Device Name", and then display the information relevant to that device
I've tried the following scripts so far:
1:
<?php
$json = file_get_contents('URLHERE');
$obj = json_decode($json);
echo $obj->DeviceID;
?>
2:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'URLHERE');
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result);
echo $result->DeviceName;
?>
3:
<?php
$url = 'URLHERE';
$obj = json_decode(file_get_contents($url), true);
echo $obj['DeviceID'];
?>
4:
<?php
$url = "URLHERE";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "Device: ". $json_data["DeviceID"];
?>
5:
<?php
$json = file_get_contents('URLHERE');
$encodeJ = utf8_encode($json);
$obj = json_decode($encodeJ);
var_dump($obj-> DeviceID);
?>
The fourth one is the closest I've managed to get to it displaying data using these methods, but rather than any information I just get "Device: NULL"
Any help would be appreciated. Starting to pull my hair out here!
UPDATE:
Have managed to make some progress with the following:
<?php
$data = file_get_contents('URLHERE');
$response = json_decode($data, true);
echo 'Device: ' . $response['Data']['0']['DeviceName'];
echo 'Device: ' . $response['Data']['1']['DeviceName'];
?>
This is displaying the device names from the array for value 0 and 1. So now I need to figure out how to iterate through the array and display each one in sequence, as opposed to hard coding each one.
Your DeviceID is in Data & it's an array so you can't access directly. When you
$data = json_decode('{"Data":[{"DeviceID":"1","DeviceName":"Phone 1","Platform":"Phone OS","Edition":"Deluxe","State":"0","Time":"2016-03-16T13:47:44+01:00"}]}', true);//I am using array so second parameter is true to easily demonstrate
Your structure is
[
"Data" => [
[
"DeviceID" => "1",
"DeviceName" => "Phone 1",
"Platform" => "Phone OS",
"Edition" => "Deluxe",
"State" => "0",
"Time" => "2016-03-16T13:47:44+01:00",
],
],
]
So to get only first DeviceID if you want then
$deviceID = isset($data['Data'][0]['DeviceID']) ? $data['Data'][0]['DeviceID'] : null;
or if you want all the DeviceIDs then
$deviceIds = [];
if (isset($data['Data']) && is_array($data['Data']))
{
foreach ($data['Data'] as $row)
{
if (isset($row['DeviceID']))
{
$deviceIds[] = $row['DeviceID'];
}
}
}
or you can use array_column if your php version is >= 5.5.0 or php 7
$deviceIds = [];
if (isset($data['Data']) && is_array($data['Data']))
{
$deviceIds = array_column($data['Data'], 'DeviceID');
}
To get the data, use:
$json = file_get_contents( $url );
Then get it into an array, as:
$arr = json_decode( $json, TRUE );
To "Display the data in a block list, as opposed to long lines", use:
foreach ( $arr AS $element ) {
foreach ( $element AS $e ) {
echo $e['DeviceName'] . '<br>';
}
}
To "Allow selection of a specific device through "Device Name", and then display the information relevant to that device", use:
$deviceName = "Phone 1"; // depending upon your use case, you'll need to decide how you want to set this variable; it's hard coded here for the sake of example
foreach ( $arr AS $element ) {
foreach ( $element AS $e ) {
if ( $e['DeviceName'] = $deviceName ) {
echo '<pre>';
print_r( $e );
echo '</pre>';
}
}
}
While it's not entirely clear what you mean by "Allow selection of a specific device through "Device Name"", I'm inclined to believe you're looking for a way to let a user select a device from the list of device names. That's not a task you can accomplish with PHP alone. You'll need to build something for the front end in HTML or Javascript that interacts with your PHP on the back end.

Getting a specific value from an array

I'm trying to get a specific column from an array for each record returned.
The array is called fields and one of the arrays in the array is locations. I'm looking for a specific column in the array called name.
Here's what I have:
foreach ($new_results as $result):?>
$locations = array_map($result->locations->location,function($obj) { return $obj->location; });
echo implode(",",$locations);
endforeach;
I'm connecting to a web service to pull this data. The above is the code that the company gave me, but they haven't tested it as far as I know. It doesn't work for me.
Here's the call to the API
$results = $connection->call('groups/getAll', $params=array("suspended" => "no","fields" =>"locations"));
$new_results = $results->groups->group;
Here's an example from the API.
{
"id": "xxxx",
"fields": {
"locations": [
"North",
"Central"
]
}
}
Any thoughts on what I'm doing wrong? I'm still very new to PHP so I may be missing something very obvious.
How to get json using curl:
How to get JSON data from Rest API by PHP Curl?
Now with that in mind you can dive a little deeper into the object manipulation in terms of the response here: Accessing JSON object elements in PHP.
//""" code from the first link
$service_url = "http://127.0.0.1:8000/api/thesis/?format=json";
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
//execute the session
$curl_response = curl_exec($curl);
//finish off the session
curl_close($curl);
$curl_jason = json_decode($curl_response, true);
print_r($curl_jason);
//""" code from the first link
&
//""" code from the second link
/*Variable passed in from the ExtJS interface as JSON object*/
$json = $_POST["newUserInfo"];
//$json = '{"USER":{"ID":"","FULL_USER_NAME":"Some Guy","ENTERPRISE_USER_NAME":"guyso01","USER_EMAIL":"Some.Guy#Email.com","USER_PHONE":"123-456-7890"},"PERMISSIONS":{"ID":"","USER_ID":"","IS_ADMIN":"true"},"SETTINGS":{"ID":"","USERS_ID":"","BACKGROUND":"default"}}';
//Test to view the decoded output
//var_dump(json_decode($json));
//Decode the $json variable
$jsonDecoded = json_decode($json,true);
//Create arrays for each table from the $jsonDecoded object
$user_info = array($jsonDecoded['USER']);
$permissions_info = array($jsonDecoded['PERMISSIONS']);
$settings_info = array($jsonDecoded['SETTINGS']);
// """ code from the first link

Json_decode returns string(0) ""

I am trying to pass data from ios to server.
Php code :
<?php
$inputJSON = file_get_contents('php://input');
$data = json_decode($inputJSON, TRUE);
var_dump($data);
?>
This gives me string(0) "". I don't know whats the meaning of this.
echo $inputJSON; gives nothing
var_dump($inputJSON); returns string(0) ""
When i print the json-string it gives me a valid string
Please find the full codes of this problem in another question of mine
Cannot able to access json array in php , it returns null and Warning: Invalid argument supplied for foreach()
I have created an example for you that what i am talking:-
1.My both file (php code file and json string file) in the same working directory.Check:- http://prntscr.com/apkbp9
2.json string file content should be:-
[
{
"email" : "",
"Name" : "Ddd",
"contact2" : "",
"ontact1" : ""
},
{
"email" : "",
"Name" : "Ddd",
"contact2" : "",
"contact1" : ""
},
{
"email" : "",
"Name" : "Dddddr",
"contact2" : "",
"contact1" : ""
}
]
Check here:- http://prntscr.com/apkbx0
3.php code file content:-
<?php
$inputJSON = file_get_contents('input.txt');
echo $inputJSON;
$data = json_decode($inputJSON, TRUE);
echo "<pre/>";print_r($data);
?>
Check here:- http://prntscr.com/apkc6x
Output on my browser:- http://prntscr.com/apkcoi
You can use CURL like below:-
<?php
function url_get_contents ($Url) {
if (!function_exists('curl_init')){
die('CURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
$inputJSON = url_get_contents('php://input');
echo $inputJSON;
$data = json_decode($inputJSON, TRUE);
echo "<pre/>";print_r($data);
?>
For more reference about CURL :- http://php.net/manual/en/book.curl.php
Note:- if both will not work, then first you need to save your json data in a file with extension .txt and then you can use both code given above, just by putting the full path of that text file.
fisrt you should check is your url is correct or not. If every thing is right but still its not showing the response use curl functionality such as alter native of file_get_content
With God Grace solved my problem-
pass true to convert objects to associative arrays, so accessing numeric/associative array like this.
$var = $data[0]['key'];
Then we use a combination of numeric and associative array syntax to access the desired element in multidimensional array.
But if i trying to var_dump($data); is retun null.
Reference tutorial: http://www.dyn-web.com/tutorials/php-js/json/decode.php

Problems parsing JSON with PHP (CURL)

I am trying to access the value for one of the currencies (e.g. GBP) within the "rates" object of the following JSON file:
JSON file:
{
"success":true,
"timestamp":1430594775,
"rates":{
"AUD":1.273862,
"CAD":1.215036,
"CHF":0.932539,
"CNY":6.186694,
"EUR":0.893003,
"GBP":0.66046,
"HKD":7.751997,
"JPY":120.1098,
"SGD":1.329717
}
}
This was my approach:
PHP (CURL):
$url = ...
// initialize CURL:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// get the (still encoded) JSON data:
$json = curl_exec($ch);
curl_close($ch);
// store decoded JSON Response in array
$exchangeRates = (array) json_decode($json);
// access parsed json
echo $exchangeRates['rates']['GBP'];
but it did not work.
Now, when I try to access the "timestamp" value of the JSON file like this:
echo $exchangeRates['timestamp'];
it works fine.
Any ideas?
Try removing (array) in front of json_decode and adding true in second parameter
Here is the solution.
$exchangeRates = (array) json_decode($json,TRUE);
https://ideone.com/LFbvUF
What all you have to do is use the second parameter of json_decode function.
This is the complete code snippet.
<?php
$json='{
"success":true,
"timestamp":1430594775,
"rates":{
"AUD":1.273862,
"CAD":1.215036,
"CHF":0.932539,
"CNY":6.186694,
"EUR":0.893003,
"GBP":0.66046,
"HKD":7.751997,
"JPY":120.1098,
"SGD":1.329717
}
}';
$exchangeRates = (array) json_decode($json,TRUE);
echo $exchangeRates["rates"]["GBP"];
?>

PHP: Get value from array

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

Categories