How to get a single value in API - php

How will i be able to get a single value out of BTC-e API using PHP?. This is the current API that i can use.
https://btc-e.com/api/3/ticker/btc_usd
As you can see, it shows lots of information, but i dont need many information that is displayed there. What can i do so that i will only get
"last":284.323
this number?
Thank you for your help regarding this subject.

As you can see, the received data is a JSON value.
If you simply want to receive data from a website, you can use the file_get_contents function.
With the json_decode function, you can create an object from this data.
If you're looking for a specific value, you maybe can use print_r to get a clarifying list of the given data.
When you use the print_r function on the given data, it will return:
stdClass Object
(
[btc_usd] => stdClass Object
(
[high] => 288.957
[low] => 272.00201
[avg] => 280.479505
[vol] => 2178508.65397
[vol_cur] => 7771.83325
[last] => 286.322
[buy] => 286.328
[sell] => 286.322
[updated] => 1445787588
)
)
As you can see, you are looking for a variable stored in ->btc_usd->last
So when it all comes together, you can use the following:
<?php
# Get String
$_ApiString = '{"btc_usd":{"high":288.957,"low":272.00201,"avg":280.479505,"vol":2178508.65397,"vol_cur":7771.83325,"last":286.322,"buy":286.328,"sell":286.322,"updated":1445787588}}';
# Or maybe you simply want to download it from a website
$_ApiString = file_get_contents('https://btc-e.com/api/3/ticker/btc_usd');
# Create object from ApiString
$_Object = json_decode($_ApiString);
# Get variable
$_Last = $_Object->btc_usd->last;
?>

Related

Can't extract data from Json

I can't extract data from json that I got from an api.
I tried for hours, tried all kinds of formats. Read Stackoverflow threads like How do I extract data from JSON with PHP?, but I can't see what I am doing wrong.
This is the code so far:
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results, true);
// Some variations I tried:
var_dump($results->status[1]);
var_dump($results->data[1]->opening_price);
var_dump($results["data"][1]["opening_price"]);
End result: NULL NULL NULL
What am I doing wrong?
Thanks for the answers! I will upvote the working ones. Seems I got confused in the formating!
<?php
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results, true);
print_r($results['status']);
echo "</br>";
print_r($results['data']['opening_price']);
Try access your array that way.
The output is :
0000
6998000
Keep an eye for the nested arrays. You need to access their parent array first in order to get their values.
Have you read the documentation of json_decode() (or, at least, the accepted answer of the question you linked)? If you pass TRUE as the second argument to json_decode() (and there is no decent reason to not pass it) then it decodes the JSON to associative arrays and not objects.
The elements in a PHP array can be accessed using the square bracket syntax.
A simple call to print_r($results) tells its structure:
Array
(
[status] => 0000
[data] => Array
(
[opening_price] => 6998000
[closing_price] => 7270000
[min_price] => 6750000
[max_price] => 7997000
[average_price] => 7188302.5804
[units_traded] => 78484.9241002
[volume_1day] => 78484.9241002
[volume_7day] => 335611.84181738
[buy_price] => 7268000
[sell_price] => 7274000
[date] => 1510563513031
)
)
Now, accessing its items is a piece of cake:
echo($results['status']);
# 0000
echo($results['data']['opening_price']);
# 6998000
Remove true from json_decode so you will have object result like Demo
$results = json_decode($api_results);
var_dump($results->status);
var_dump($results->data->opening_price);
When you use json_decode with true the returned objects will be converted into associative arrays.
Use this code like i think work it fine..
<?php
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results);
print_r($results);
var_dump($results->status);
$var = $results->data;
var_dump($var->opening_price);
?>
stdClass Object
(
[status] => 0000
[data] => stdClass Object
(
[opening_price] => 6998000
[closing_price] => 7270000
[min_price] => 6750000
[max_price] => 7997000
[average_price] => 7188302.5804
[units_traded] => 78484.9241002
[volume_1day] => 78484.9241002
[volume_7day] => 335611.84181738
[buy_price] => 7268000
[sell_price] => 7274000
[date] => 1510563513031
)
)
string(4) "0000"
string(7) "6998000"
Remove true from json_decode and try something like this:
var_dump($results->status);
var_dump($results->data->opening_price);
If you see {} it is refering to objects and [] indicates that it is an array. You're trying to show everything as if they were arrays
You have set the second parameter of json_decode() to true. that means the json will be converted to an array so you are not able to access the data using pointer -> (because it is not an object).
You may access the data like this:
var_dump($results['status'][0]);
var_dump($results['data'][0]['opening_price']);
P.S: Try var_dump($results) to see the exact data, so you know how to access each attribute.

Nested Array Foreach Issue

I am very basic new php learner, i having difficulty to get nested array value, here is my json result:
stdClass Object
(
[title] => Aao Raja - Gabbar Is Back | Chitrangada Singh
[link] => stdClass Object
(
[22] => Array
(
[0] => http://r8---sn-aigllnsk.c.docs.google.com/videoplayback?mime=video%2Fmp4&id=o-AExJcTxRDvCYsfgA1cIvQDs1v-pvLhKjTPdDh67X19vz&dur=145.542&itag=22&pl=48&ip=2a03:b0c0:1:d0::2f6:c001&sparams=dur,expire,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,nh,pl,ratebypass,source,upn&key=cms1&sver=3&expire=1437035009&upn=9lTw9Popb18&ratebypass=yes&source=youtube&lmt=1432539432699196&fexp=901816%2C9407809%2C9408142%2C9408420%2C9408710%2C9409172%2C9412774%2C9412846%2C9413149%2C9415664%2C9415958%2C9416126%2C9416370%2C9416656&ipbits=0&signature=3547894526817B37774A7838F8B68493CDD62101.3F143C74D76E8705800445A4CD4476C4F8BCD988&cms_redirect=yes&mm=31&mn=sn-aigllnsk&ms=au&mt=1437013301&mv=m&nh=IgpwcjAzLmxocjE0KgkxMjcuMC4wLjE&utmg=ytap1
[1] =>
[2] => hd720
)
[43] => Array
(
[0] => http://r8---sn-aigllnsk.c.docs.google.com/videoplayback?mime=video%2Fwebm&id=o-AExJcTxRDvCYsfgA1cIvQDs1v-pvLhKjTPdDh67X19vz&dur=0.000&itag=43&pl=48&ip=2a03:b0c0:1:d0::2f6:c001&sparams=dur,expire,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,nh,pl,ratebypass,source,upn&key=cms1&sver=3&expire=1437035009&upn=9lTw9Popb18&ratebypass=yes&source=youtube&lmt=1428933984759484&fexp=901816%2C9407809%2C9408142%2C9408420%2C9408710%2C9409172%2C9412774%2C9412846%2C9413149%2C9415664%2C9415958%2C9416126%2C9416370%2C9416656&ipbits=0&signature=266C126464ECDB4CC0FF076CD41F07BCC4DA7E34.08D9F13B7BF7D92FD1E1963336CC7FB8F19FE899&cms_redirect=yes&mm=31&mn=sn-aigllnsk&ms=au&mt=1437013301&mv=m&nh=IgpwcjAzLmxocjE0KgkxMjcuMC4wLjE&utmg=ytap1
[1] =>
[2] => medium
)
I can access the Title, but can't access the Link urls:
echo $title = $json->{'title'};
echo $link = $json->{'link'}->{'22'}->{'0'};
How can access the specific link array 22
This echo $title = $json->{'title'}; works because you are accessing an object's property and using -> is the correct way.
In this case $json->{'link'}->{'22'}->{'0'} you are trying to access an array item instead an object's property, because $json->{'link'}->{'22'} is an array and not an object. In this case, you should access it in this way: $json->{'link'}->{'22'}[0]. In order to avoid this kind of issues and, when you decode your JSON to a PHP object, you can pass true as a second parameter to the function json_decode and that will convert the whole object into an array. That way, you don't need to worry about accessing elements as object's attributes, you can access them, always, as array items. So, in this case, it would be: $json["link"]["22"][0].
You're confusing the way you access objects and arrays.
Getting the title is correct via $json->title, but the link should be $json->link->{'22'}[0] - a mixture of objects and arrays.
FYI the {'name'} notation is the same as name - only required when you are including variables in your object name e.g. {$someVar . 'name'}
I suppose you use json_decode() function. Do you know that you can get an array instead of StdClass Object? So, you can use.
<?php
$php_array = json_decode($json_string, true);

view query empty when only using 1 or 2 characters in couchDB/Php

Using the php couchbase sdk, and i've got a view which indexes various object types.
hitting the view directly returns results no problem
http://127.0.0.1:8092/default/_design/dev_domain/_view/search?stale=false&connection_timeout=60000&limit=10&skip=0&startkey=%22S%22&endkey=%22S\u02ad%22
Which returns happily
{"total_rows":700,"rows":[
{"id":"TestCompany\\Model\\SampleObject\\b63008d6d65df09a6947a9c3ebb9f3137ed3c54ac3754a21ba2098d80537c3ef","key":"sam","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\f6b4119f7373edb6cfc7901702a2bb81b655834cd009cdfcaaafbaa1991f2cc4","key":"sam","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\b63008d6d65df09a6947a9c3ebb9f3137ed3c54ac3754a21ba2098d80537c3ef","key":"samp","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\f6b4119f7373edb6cfc7901702a2bb81b655834cd009cdfcaaafbaa1991f2cc4","key":"samp","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\b63008d6d65df09a6947a9c3ebb9f3137ed3c54ac3754a21ba2098d80537c3ef","key":"sampl","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\f6b4119f7373edb6cfc7901702a2bb81b655834cd009cdfcaaafbaa1991f2cc4","key":"sampl","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\b63008d6d65df09a6947a9c3ebb9f3137ed3c54ac3754a21ba2098d80537c3ef","key":"sample","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\f6b4119f7373edb6cfc7901702a2bb81b655834cd009cdfcaaafbaa1991f2cc4","key":"sample","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\b63008d6d65df09a6947a9c3ebb9f3137ed3c54ac3754a21ba2098d80537c3ef","key":"sampled","value":"SampleData"},
{"id":"TestCompany\\Model\\SampleObject\\f6b4119f7373edb6cfc7901702a2bb81b655834cd009cdfcaaafbaa1991f2cc4","key":"sampled","value":"SampleData"}
]
}
But using the php sdk:
$test = $cb->view("dev_domain", "search",array("startkey"=>"s","endkey"=>"s"."\u02ad"));
return no results, using 3 or more keys is fine, ie:
$test = $cb->view("dev_domain", "search",array("startkey"=>"sam","endkey"=>"sam"."\u02ad"));
Array
(
[total_rows] => 700
[rows] => Array
(
[0] => Array
(
[id] => Authentic\Model\SampleObject\b63008d6d65df09a6947a9c3ebb9f3137ed3c54ac3754a21ba2098d80537c3ef
[key] => sam
[value] => SampleData
)
[1] => Array
(
[id] => Authentic\Model\SampleObject\f6b4119f7373edb6cfc7901702a2bb81b655834cd009cdfcaaafbaa1991f2cc4
[key] => sam
[value] => SampleData
)
)
)
I can't figure out how to pipe the sdk through charles (proxy) so not having any luck debugging that..
The problem here is that \u02ad is already JSON encoded, and so when you provide that to the CouchDB SDK in PHP it's going to get re-encoded (probably to \\u02ad which won't result in what you want by the time it gets to CouchDB itself).
You should either include the literal Unicode character in your string, or wrap your unicode string in a json_decode wrapper so that it's decoded before being passed into the SDK method, eg:
"endkey"=>"s".json_decode('"\u02ad"')
Note the single quotes around the double quoted sequence.
at the end of the day, of course my data was only indexed at 3 characters and over (as shown in the sample) , so my bad.

PHP - search for a key value and then find the value of another key in the same object subarray

I've searched a lot for this, and found several similar questions, but none quite address what I'm trying to accomplish.
I'm trying to write a code that will search a PHP (multi)multidimensional array to see which subarray contains the unique key value that I have. Then I would like it to return the value of a different key in that same object subarray.
$Arraytosearch = Array(
.
//various other subarrays
.
[fields] => Array (
.
.
.
//I don't know the number of the object subarray
[x] => PodioTextItemField Object (
[__attributes] => Array (
[field_id] => 37325091
[type] => text
[external_id] => id
[label] => ID
[values] => Array (
[0] => Array (
[value] => REF100019 ) )
[config] => Array (
[description] => [settings] => Array (
[size] => small )
[required] => [mapping] => [label] => ID [visible] => 1 [delta] => 2 ) )
.
.
.
//(and so on)
I'd like to write a function that will return "REF100019" by supplying the value of the field_id => 37325091.
Some things I have tried that I couldn't get to work:
foreach
and new RecursiveIterator although the tutorials I read weren't useful for my case here.
Even though the array looks complicated, I think it will be easy since I already have the field id of the parent array.
Thank you in advance for any guidance or sample codes that will work!
Background: This is a part of the response I get from Podio after submitting a request to their API. I just don't know how to take that response and get the piece I need (the ID) so that I can echo it for users).
EDIT: Thank you Orangepill and Barmar for the support. I tried your code. But was getting an error, which made me realize I hadn't given you the full array. I figured out how to get the Podio response to display in a more readable format (I was reading the full JSON response before from the Podio debug file which was super confusing), and figured out the full array is actually structured as I have shown below.
I then took your code and was able to figure out how to make it work for my scenario (see below). Very proud of myself considering I have never written any code before, but I couldn't have done it without your help! Thanks again!
$Arraytosearch = Array(
[items] => Array(
[0] => PodioItem Object(
[_attributes] => Array(
[fields] => Array (
[x] => PodioTextItemField Object (
[__attributes] => Array(
[field_id] => 37325091
[values] => Array(
[0] => Array(
[value] => REF100019 ) )
Note: For anyone who is new to programming like myself and wants the Podio response (or any JSON string) to display in a "pretty" readable format like above, use the code (from Display an array in a readable/hierarchical format thanks to Phenex):
print "<pre>";
print_r($Arraytoformat);
print "</pre>";
And finally, the full code I used (using Orangepill's answer below) which searches the objects and arrays and gives me what I have been searching for for days now is as follows:
$Arraytosearch = PodioItem::filter(APP_ID, $filterParams);
$fieldID = 37325091;
function getFirstValueByFieldId($fieldId, $Arraytosearch){
foreach($Arraytosearch["items"][0]->__attributes["fields"] as $textitem){
if ($textitem->__attributes["field_id"] == $fieldId){
return $textitem->__attributes["values"][0]["value"];
}}}
$refID = getFirstValueByFieldId($fieldID, $Arraytosearch);
The podio-php library has built-in methods that handle all this for you. There's no need to mess with the __attributes property yourself.
You can see a bunch of examples at https://github.com/podio/podio-php/blob/master/examples/items.php
In your case:
// Get item collection
$itemCollection = PodioItem::filter(APP_ID, $filterParams);
$fieldID = 37325091;
foreach ($itemCollection['items'] as $item) {
// Get the field from the item
$field = $item->field($fieldID);
// Now you can print the value of that field
print $field->humanized_value;
// Or if you don't want to have the content sanitized:
print $field->values[0]['value'];
}
There is a lot of ways to skin this cat... this is probably the most straight forward
function getFirstValueByFieldId($fieldId, $Arraytosearch){
foreach($Arraytosearch["fields"] as $textitem){
if ($textitem->__attributes["field_id"] == $fieldId){
return $textitems->__attributes["values"][0]["value"];
}
}
}
to Use in your case would be
echo getFirstValueByFieldId("37325091", $Arraytosearch);
Basically it walks the elements in the fields array and returns the value in the first associated value in the values array where field_id is equal to the parameter of the function.

How to access the members of this data in PHP?

Okay. Now I give up. I have been playing with this for hours.
I have a variable name $data.
The variable contains these contents: (extracted by using var_export())
array (
'headers' =>
array (
'content-type' => 'multipart/alternative; boundary="_689e1a7d-7a0a-442a-bd6c-a1fb1dc2993e_"',
),
'ctype_parameters' =>
array (
'boundary' => '_689e1a7d-7a0a-442a-bd6c-a1fb1dc2993e_',
),
'parts' =>
array (
0 =>
stdClass::__set_state(array(
'headers' =>
array (
'content-type' => 'text/plain; charset="iso-8859-1"',
'content-transfer-encoding' => 'quoted-printable',
),
'ctype_primary' => 'text',
)),
),
)
I removed some non-essential data.
I want to access the headers value (on the second line above) - simple: $data->headers
I want to access the headers value (on the fourteenth line after the stdClass:: stuff) - how?
How can I possibly access the values within the stdClass::__set_state section?
I tried var_export($data->parts); but all I get is
NULL
Is this variable declared the way you posted it? Like:
$data = array(
'headers' =>
array (
…
In that case, I'm not quite sure how you can access 'headers' via $data->headers. It should be $data['headers'], because it is an array, not an object.
Further down, stdClass::__set_state(array('headers' => …)) statically calls the method __set_state of the class stdClass. Whatever this method does I don't know, but only its return value will be assigned to the 'parts' => array(0 => ...) key.
If OTOH what you're showing is the result of var_dump($data), then this is incorrect nonsense, since stdClass::__set_state() would never show up in a var_dump. Something is fishy either in your code or in what you posted and it's hard to say without seeing more of it.
Disregard the above, var_export prints classes this funky way.
$data['headers'] should do it for the first headers part. Further down, $data['parts'][0]->headers should do the trick.
I ran into a similar problem with the open-source mail server Postal. In this case, I used the API to send an email message with two recipients. The API returns JSON, which I want to process to get the message ID Postal has assigned to each message. The JSON string decodes to a series of nested objects, according to print_r.
pObj: stdClass Object
(
[status] => success
[time] => 0.28
[flags] => stdClass Object
(
)
[data] => stdClass Object
(
[message_id] => a122e786-6c32-4085-b1ed-023e5923ca38#rp.postal.domain.com
[messages] => stdClass Object
(
[name1#domain1.com] => stdClass Object
(
[id] => 180
[token] => AblVpj6UW2wh
)
[name2#domain2.com] => stdClass Object
(
[id] => 181
[token] => io5wgEXO1boH
)
)
)
)
Looking at the structure, the first few layers are easy to extract. The trouble is that the messages object has attributes named for each recipient email address. Without knowing these address values a priori, I couldn't access the individual recipient objects programmatically to get at the message id.
I also examined this object using var_dump() and var_export(). That's where I saw this strange and misleading syntax: "stdClass::__set_state(array(". But there are no arrays at all in this object. In reality, this structure contains nothing but nested objects and attributes.
This situation was giving me fits until I asked the right question: what are the names of an object's attributes?
Now the programmatic solution is relatively easy because PHP has a function for that. I used get_object_vars() to get an array of attributes in the messages object. By simply looping on that array, I could then access the id and token attributes of each address. Here's the code, with a sample JSON response from Postal.
define('_EOL', "\n");
$json='{"status":"success","time":0.28,"flags":{},"data":{"message_id":"a122e786-6c32-4085-b1ed-023e5923ca38#rp.postal.domain.com","messages":{"name1#domain1.com":{"id":180,"token":"AblVpj6UW2wh"},"name2#domain2.com":{"id":181,"token":"io5wgEXO1boH"}}}}';
$pObj=json_decode($json);
$str='<pre>pObj: '.print_r($pObj, true)._EOL._EOL;
$str.=' - status='.$pObj->status._EOL;
$msgVars=get_object_vars($pObj->data->messages);
foreach ($msgVars as $varKey=>$msgObj)
{
$str.=' - '.$varKey.':'._EOL;
$str.=' - id='.$msgObj->id._EOL;
$str.=' - token='.$msgObj->token._EOL;
}
echo($str.'</pre>');
What made this hard is that the Postal design uses variable attribute names in the messages object. I would have made messages an array and put the email address into an attribute named address along with the attributes id and token. But it is what it is, and I hope this helps someone else.

Categories