Trying to get the single value from google finances api. I can retrieve the data perfectly however when I try to echo out a single value it doesn't seem to work. Can anyone help?
My code is:
$request = wp_remote_get('http://www.google.com/finance/info?q=NASDAQ%3aGOOG', $args );
$price = wp_remote_retrieve_body( $request );
print_r($price);
The output is:
// [
{
"id": "304466804484872"
,"t" : "GOOG"
,"e" : "NASDAQ"
,"l" : "533.75"
,"l_fix" : "533.75"
,"l_cur" : "533.75"
,"s": "2"
,"ltt":"4:01PM EST"
,"lt" : "Dec 2, 4:01PM EST"
,"lt_dts" : "2014-12-02T16:01:56Z"
,"c" : "-0.05"
,"c_fix" : "-0.05"
,"cp" : "-0.01"
,"cp_fix" : "-0.01"
,"ccol" : "chr"
,"pcls_fix" : "533.8"
,"el": "533.00"
,"el_fix": "533.00"
,"el_cur": "533.00"
,"elt" : "Dec 2, 7:59PM EST"
,"ec" : "-0.75"
,"ec_fix" : "-0.75"
,"ecp" : "-0.14"
,"ecp_fix" : "-0.14"
,"eccol" : "chr"
,"div" : ""
,"yld" : ""
}
]
I've tried echoing out the single value, adding a foreach statement and then echoing out the value based on 'l_fix' and the 'id', and also tried splitting the string up but it wouldn't work.
Thanks
Do it:
$request = wp_remote_get('http://www.google.com/finance/info?q=NASDAQ%3aGOOG', $args );
$data = wp_remote_retrieve_body( $request );
$data = str_replace('//','',$data);
$data = json_decode($data);
$price = $data[0]; // $price = array_shift($data);
print $price->l_fix .....
Google APIs (in this specific case) return JSON with two first chars ('//').
Related
This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 5 years ago.
{
"took" : 363,
"timed_out" : false,
"num_reduce_phases" : 15,
"_shards" : {
"total" : 7195,
"successful" : 7195,
"failed" : 0
},
"hits" : {
"total" : 35672,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"2" : {
"doc_count_error_upper_bound" : 54,
"sum_other_doc_count" : 1463,
"buckets" : [
{
"key" : "ふるさと納税",
"doc_count" : 30376
}
]
}
}
}
This is the json file . I need to access the doc_count field.
I am trying to do it like this
$trend_words = json_decode($file);
$aggregations = $trend_words->aggregations;
$buckets = $aggregations->{2}->buckets->{0};
But its not working.
Can someone help.
$trend_words = json_decode($file,true);
$aggregations = $trend_words['aggregations']['2']['buckets'][0]['doc_count'];
print_r($aggregations)
You should use ,true otherwise you will get an stdclass object and not an array you want.
try this
<?php
$sJson = '
{
"took" : 363,
"timed_out" : false,
"num_reduce_phases" : 15,
"_shards" : {
"total" : 7195,
"successful" : 7195,
"failed" : 0
},
"hits" : {
"total" : 35672,
"max_score" : 0.0,
"hits" : [ ]
},
"aggregations" : {
"2" : {
"doc_count_error_upper_bound" : 54,
"sum_other_doc_count" : 1463,
"buckets" : [
{
"key" : "ふるさと納税",
"doc_count" : 30376
}
]
}
}
}
';
$aJson = json_decode($sJson, true);
echo $aJson['aggregations'][2]['buckets'][0]['doc_count'];
https://3v4l.org/kHfdo
Here is the answer, As the buckets increases you need to have a loop through to read all the buckets
$trend_words = json_decode($file, true);
$aggregations = $trend_words['aggregations'][2];
$buckets = array();
foreach($aggregations as $element)
$buckets[] = $element['buckets'];
print_r($buckets);
Make Json to array and try
$trend_words = json_decode($file, true);
$aggregations = $trend_words['aggregations'];
$buckets =$aggregations[2]['buckets'][0];
In my $output there is this:
{
"status" : "success",
"data" : {
"network" : "BTC",
"addresses" : [
{
"user_id" : 0,
"address" : "3ABR5GohqyXzf2zebYwjmLuwV7vtFZw1BZ",
"label" : "default",
"available_balance" : "0.00000000",
"pending_received_balance" : "0.00000000"
}
]
}
}
But now I want it to get to redirect like:
https://example.com/index.php?status=succes&network=BTC
etc. etc.
But $output can change to like:
{
"status" : "success",
"data" : {
"network" : "BTC",
"available_balance" : "0.00000000",
"pending_received_balance" : "0.00000000"
}
}
But then I still want it to work.
I don't know PHP enough for this, so I want to ask:
How to do this?
Simply json_decode() and access the status and network properties:
$decoded = json_decode($output);
header('Location: https://example.com/index.php?status=' . urlencode($decoded->status) . '&network=' . urlencode($decoded->data->network));
exit();
Get the data in the json as an array:
$url = 'https://example.com/index.php?status=' . $status;
foreach($data as $param->$value) {
$url += '&' . $param . '=' . $value
}
header('Location:' $url);
Been a while since i've worked in php but this should handle a varying amount of parameters.
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 6 years ago.
how can I select the number of "total_items" and the "average_price"?
JSON:
{
"status" : "success",
"data" : {
"items" : [
{
"market_hash_name" : "AK-47 | Redline (Field-Tested)",
"total_items" : 698,
"lowest_price" : "3.90",
"highest_price" : "300.00",
"cumulative_price" : "4669.62",
"recent_sales_info" : {
"hours" : "17.94",
"average_price" : "4.23"
}
}
]
}
}
Thats my PHP-Script:
$link = 'skin.json';
$string = file_get_contents($link);
$obj = json_decode($string, TRUE);
$name = $obj['items']['market_hash_name'];
$itmes = $name['total_items'];
$itmes = $name['average_price'];
How can I save the number of "total_items" and the "average_price" in variables?
Thank You
Regards.
Enge
Just like Andreas wrote, or :
// first, new variable (shorter lines/less depth afterwards)
$article = $obj['data']['items'][0];
// then
$total_items = $article['total_items'];
$avg_price = $article['recent_sales_info']['average_price'];
Enge, note that "items": [ is an opening array within JSON object, that's the zero You were missing...
Try this:
$total_items = $obj['data']['items'][0]['total_items'];
$avg_price = $obj['data']['items'][0]['recent_sales_info']['average_price'];
Im trying to do a loop through a pretty large json file with this function someone else helped me with. But the code below returns with : Warning: Invalid argument supplied for foreach()
This code is executed before the function:
$file = new SplFileObject("bdfile/summoner_leagues_entries_export.json");
while (!$file->eof())
{
$json = json_decode($file->fgets(), true);
var_dump($json);
}
_
function getentry($json)
{
foreach($json as $league)
{
if($league['queue'] == 'RANKED_SOLO_5x5')
{
return $league['entries'][0];
}
return null;
}
}
$entry = getentry($json);
if(isset($entry)) echo $entry['playerOrTeamName'] . ',' . "</br>";
this is the output of var_dump($json); (just a tiny example because its a large file):
{
"_id" : ObjectId("540449a4f59600af7d285075"),
"leagues" : [{
"name" : "Cassiopeia's Hunters",
"tier" : "GOLD",
"queue" : "RANKED_SOLO_5x5",
"entries" : [{
"playerOrTeamId" : "21893177",
"playerOrTeamName" : "JoKoksa",
"division" : "III",
"leaguePoints" : NumberLong(5),
"wins" : NumberLong(99),
"isHotStreak" : false,
"isVeteran" : false,
"isFreshBlood" : false,
"isInactive" : false,
"miniSeries" : false
}],
"id" : NumberLong(21893177)
}, {
"name" : "Kayle's Patriots",
"tier" : "BRONZE",
"queue" : "RANKED_TEAM_3x3",
"entries" : [{
"playerOrTeamId" : "TEAM-ffbaccc0-b8c0-11e2-b67a-782bcb497d6f",
"playerOrTeamName" : "EloStechers",
"division" : "II",
"leaguePoints" : NumberLong(64),
"wins" : NumberLong(9),
"isHotStreak" : false,
"isVeteran" : false,
"isFreshBlood" : false,
"isInactive" : false,
"miniSeries" : false
}],
"id" : NumberLong(21893177)
}, {
"name" : "Cassiopeia's Infiltrators",
"tier" : "BRONZE",
"queue" : "RANKED_TEAM_5x5",
"entries" : [{
"playerOrTeamId" : "TEAM-ffbaccc0-b8c0-11e2-b67a-782bcb497d6f",
"playerOrTeamName" : "EloStechers",
"division" : "II",
"leaguePoints" : NumberLong(60),
"wins" : NumberLong(11),
"isHotStreak" : false,
"isVeteran" : false,
"isFreshBlood" : false,
"isInactive" : true,
"miniSeries" : false
}],
"id" : NumberLong(21893177)
}],
"summonerId" : NumberLong(21893177),
"region" : "euw",
"updatedAt" : NumberLong(1412719896)
}
EDIT 3:
$file = new SplFileObject("bdfile/summoner_leagues_entries_export.json");
while (!$file->eof()) {
$json = json_decode($file->fgets(), true);
foreach($json['leagues'] as $entry) {
echo $entry['entries'][0]['playerOrTeamName'] . ',' . $entry['tier'] . ',' . $entry['entries'][0]['division'] . ',' . $entry['entries'][0]['leaguePoints'] . ',' . $entry['entries'][0]['wins'] . "<br/>";
}
}
$file = null;
EDIT 4:
I got it fixed, if you are interested, i can paste code here.
I think your line in getentry($json)
foreach($json as $league)
should be
foreach($json['leagues'] as $league)
On reflection. That doesn't look like a vardump. Probably $json is just a string when you get into getentry.
Perhaps you need a bson_decode function before you will be able to treat it like a hash (array)
json_decode won't handle it.
There is one in mongo for php.
http://php.net/manual/en/function.bson-decode.php
But it does say "This function is very beta and entirely useless for 99% of users. It is only useful if you're doing something weird, such as writing your own driver on top of the PHP driver."
I have json result from API like:
{
"pagination":
{
"results" : 2248,
"page" : 1,
"page_size" : 200,
**"pages" : 12**
},
"products" :
[ {"id": "370c3876-a2b9-11e2-b2b4-bc764e10976c", "source_id": "",....}]}
I would like to retrieve "pages" : 12 from pagination. How can I do it?
I tried this and it worked fine
$data = ' {
"pagination":
{
"results" : 2248,
"page" : 1,
"page_size" : 200,
"pages" : 12
}
}';
$response = json_decode($data, true);
echo $response['pagination']['pages'];//12
Use json_decode to decode the api response, then access the property.
Example:
$response = json_decode($data, true);
echo $response['pagination']['pages'];
<?php
$object = json_decode($your_api_return_string);
$pages = $object->pagination->pages;
echo $pages;
?>