php request to display datas from a webpage - php

I'm a teacher in a primary school et we're part of the weatherstation project with raspberry pi
we have a website with our measurements : http://meteovictorhugo.ddns.net:1800/demo
everything is working.
Now, we'd like to have measurements from other stations in the world tu study them and work in sciences, geography...
We can have them here : https://apex.oracle.com/pls/apex/raspberrypi/weatherstation/getalllastmeasurement
but it's not really readable for pupils
First, we would like to extract datas to put them in a table and in a second time be able to choose which station we want to display
It's a bit difficult for us
All I succeed to do is this :
$json = file_get_contents('https://apex.oracle.com/pls/apex/raspberrypi/weatherstation/getalllastmeasurement');
$json = utf8_encode($json);
$obj = var_dump(json_decode($json));
echo $obj;
which gives us, meteovictorhugo.ddns.net:1800/demo/world.php so as to say nothing ...
If someone has an idea, we will be very grateful and you'll help pupils (and their teacher) to learn things
I also try with this
$json = file_get_contents('https://apex.oracle.com/pls/apex/raspberrypi/weatherstation/getalllastmeasurement');
$json = utf8_encode($json);
$obj = var_dump(json_decode($json));
foreach ($obj->items as $value) {
$ground_temp = isset($value->humidity) ? $value->humidity : 'N/A';
echo $value->weather_stn_name . ' : ' . $ground_temp . '<br/>';
}
?>
which gives this : meteovictorhugo.ddns.net:1800/demo/world4.php
Thank you
jerome

You don't need to utf8_encode the string:
<?php
$json = file_get_contents('https://apex.oracle.com/pls/apex/raspberrypi/weatherstation/getalllastmeasurement');
$decodedData = json_decode($json, true);
print_r($decodedData); // prints all data as array
print_r($decodedData['ground_temp']); //access ground_temp temperature key

Related

How get in PHP value from array JSON response of influxdb

I apologize in advance if there was already a similar question. I tried to find a solution but unfortunately I still can't.
I have a JSON response from influxdb
$output2 = '{"results": [{"statement_id": 0,"series": [{"name": "dbinfluxdb","columns": ["time","count"],"values": [["2020-07-02T00:00:00Z",1],["2020-07-03T00:00:00Z",0],["2020-07-04T00:00:00Z",0],["2020-07-05T00:00:00Z",0],["2020-07-06T00:00:00Z",1],["2020-07-07T00:00:00Z",0]]}]}]}';
and I need to print out the name of columns time and count and values to be able generate a new JSON for Google chart.
What am I able to do now is only get a statement_id=0.
$decode = json_decode($output2,true);
foreach($decode['results'] as $val){
//Actual statement_id is 0
echo "statement_id is ";
echo $val['statement_id'];
echo "<br/>";
}
But I need to print:
time, count<br/>
2020-07-02T00:00:00Z,1<br/>
2020-07-03T00:00:00Z,0<br/>
2020-07-04T00:00:00Z,0<br/>
2020-07-05T00:00:00Z,0<br/>
2020-07-06T00:00:00Z,1<br/>
or put it into the variable to be able to work with it. I already tried without converting into array just with
$decode = json_decode($output2); //without ",true"
Can you please help me how to solve it.
I've spent almost the whole day looking for a solution and I can't find a way to solve the problem.
If you need to print it out on html, just change the \n to <br>
<?php
$output2 = '{"results": [{"statement_id": 0,"series": [{"name": "dbinfluxdb","columns": ["time","count"],"values": [["2020-07-02T00:00:00Z",1],["2020-07-03T00:00:00Z",0],["2020-07-04T00:00:00Z",0],["2020-07-05T00:00:00Z",0],["2020-07-06T00:00:00Z",1],["2020-07-07T00:00:00Z",0]]}]}]}';
$decode = json_decode($output2,true);
echo $decode["results"][0]["series"][0]["columns"][0].",".$decode["results"][0]["series"][0]["columns"][1]."\n";
foreach($decode["results"][0]["series"][0]["values"] AS $el)
{
echo $el[0].",".$el[1];
echo "\n";
}
?>
If i understand you write this would be the code to output the JSON for the Google Chart:
<?php
$output2 = '{"results": [{"statement_id": 0,"series": [{"name": "dbinfluxdb","columns": ["time","count"],"values": [["2020-07-02T00:00:00Z",1],["2020-07-03T00:00:00Z",0],["2020-07-04T00:00:00Z",0],["2020-07-05T00:00:00Z",0],["2020-07-06T00:00:00Z",1],["2020-07-07T00:00:00Z",0]]}]}]}';
$decode = json_decode($output2,true);
$googlechart = array();
$googlechart[] = array($decode["results"][0]["series"][0]["columns"][0],$decode["results"][0]["series"][0]["columns"][1]);
foreach($decode["results"][0]["series"][0]["values"] AS $el)
{
$googlechart[] = array($el[0],$el[1]);
}
echo json_encode($googlechart);
?>

I want to show all result from an api

I'm working with google places API , and i showed content from the api but one by one like this
<?php
$str = file_get_contents('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=48.075971700000004,-0.7651981999999999&radius=5000&type=restaurant&keyword=cruise&key=AIzaSyDxXV4Ka8yiDq1-UKzlzX-MUC8csfdN8y4');
$maps_url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=48.075971700000004,-0.7651981999999999&radius=5000&type=restaurant&keyword=cruise&key=AIzaSyDxXV4Ka8yiDq1-UKzlzX-MUC8csfdN8y4';
$maps_json = file_get_contents($maps_url);
$maps_array = json_decode($maps_json, true);
$lat = $maps_array['results'][1]['name'];
$lat2 = $maps_array['results'][2]['name'];
echo $lat;
echo "<br>";
echo $lat2;
?>
but i want to show all the result one time with a loop
Try
foreach ($maps_array['results'] as $map) {
echo $map['name'];
echo "<br>";
}
Put the results array in a foreach and make a loop from that. in that way u will get all the data instead of taking it 1 by 1. And for the numbers array u can add a ++ statement(not needed).
hope this helps. Good luck

PHP why won't this JSON decode

SOLVED - html_entity_decode was the solution
My JSON is not decoding. Can anyone spot my mistake?
The JSON string looks like this:
{"ustaAddr":"1198 Industrial Way","ustaCity":"Carmel, CA","ustaPCode":"90210"}
Here is the code:
$newShipTo = stripslashes($aTrans['new_ship_to']);
if ($newShipTo != ""){
$arrShipToAddr = json_decode($newShipTo, TRUE);
$buyer_addr = $arrShipToAddr['ustaAddr'];
$buyer_city = $arrShipToAddr['ustaCity'];
$buyer_pcode= $arrShipToAddr['ustaPCode'];
$shipTo_addr = 'TEST' . '<p>' .$buyer_addr. '</p><p>'.$buyer_city. '</p><p>'.$buyer_pcode. '</p>' ;
}
echo $shipTo_addr;
Result:
TEST
I also tried this:
$shipTo_addr = $arrShipToAddr['ustaAddr'] .' - '. $newShipTo;
Result:
- {"ustaAddr":"1198 Industrial Way","ustaCity":"Carmel, CA","ustaPCode":"90210"}
I also tried this:
$shipTo_addr = $arrShipToAddr->ustaAddr .' - '. $newShipTo;
Result:
- {"ustaAddr":"1198 Industrial Way","ustaCity":"Carmel, CA","ustaPCode":"90210"}
Can anyone spot what I've done wrong? I can't see it...
UPDATE:
The json_decode() statement is failing, but I can't see why.
$shipTo_addr = (is_array($arrShipToAddr)) ? 'yes' : 'no';
Returns "no"
Update Two:
I hard-coded the text string (copy/pasted from the screen result from above test output!), and it worked! (Of course, that's not a solution as the JSON string is dynamically created elsewhere and retrieved from MySQL).
$newShipTo = '{"ustaAddr":"1198 Industrial Way One","ustaCity":"Carmel, CA Two","ustaPCode":"90210 Free"}';
if ($newShipTo != ""){
$arrShipToAddr = json_decode($newShipTo, TRUE);
$shipTo_addr = (is_array($arrShipToAddr)) ? 'yes' : 'no';
}
Result:
yes
I also tried these promising suggestions, but no joy:
$newShipTo = json_encode(stripslashes($aTrans['new_ship_to'])); //re-encode using PHP json_encode
and
$arrShipToAddr = json_decode(utf8_encode($newShipTo), TRUE); //force utf8
It works for me, but you can try :
$arrShipToAddr = json_decode(utf8_encode($newShipTo), TRUE);
Try this:
$newShipTo = '{"ustaAddr":"1198 Industrial Way","ustaCity":"Carmel, CA","ustaPCode":"90210"}';
which then can be decoded it into an array.
Well guys, someone over here asked if there was anything unusual about the field type in the database.
The data, as stored in the field, was html_entitied (looked like this):
{\"ustaAddr\":\"1198 Industrial Way Here\",\"ustaCity\":\"Carmel, CA We\",\"ustaPCode\":\"90210 Go\"}
However, after using stripslashes and json_decode, the string outputted like this:
{"ustaAddr":"176 Industrial Drive","ustaCity":"Carmel, CA","ustaPCode":"90210"}
At first, I thought it was the TEXT field type and thought that changing to a VARCHAR was the solution. Nope.
Using stripslashes and json_decode wasn't enough. To solve the problem, I had to do this:
$newShipTo = stripslashes(html_entity_decode($aTrans['new_ship_to']));
So, the complete code block:
$newShipTo = stripslashes(html_entity_decode($aTrans['new_ship_to']));
if ($newShipTo != ""){
$arrShipToAddr = json_decode($newShipTo, TRUE);
$buyer_addr = $arrShipToAddr['ustaAddr'];
$buyer_city = $arrShipToAddr['ustaCity'];
$buyer_pcode= $arrShipToAddr['ustaPCode'];
$shipTo_addr = '<p>' .$buyer_addr. '</p><p>'.$buyer_city. '</p><p>'.$buyer_pcode. '</p>' ;
}

PHP foreach null or else?

I'm using a basic LAMP server for my website and looking to rewrite a script I have that's linked with Twitch's API. The issue that I'm having is trying to find, for lack of a better word, the opposite of the foreach.
For example I have an array of names that are sent with a URL to the Twitch servers, and if one of the names are currently streaming "streams" will have lots of values, and if they aren't currently streaming "streams" will return null.
This works wonderful for checking people and showing they are online, but I also need it to display the ones who are offline and I can't figure out how to do that. Something like a foreachelse or something like that. This is the code I have below. Thanks.
<?php
$username = array("zeromi", "aerosgw", "krylen","tshirt_aion","snooky_aion","vashiro","papa456","vinley_aion","hanfkrokette","wtfast_siel","neckofthewood","paraproc","aionnae","uhiwi","mufflermankr","valorium","knighterrantry","soulune","relizex3","vinlockz","trevyn201","tiger529","xkegi","logsnsticks","meowform","uzuk3","kalzard01","squall_m","suyji","headpcgamer","sariett_siel");
$callAPI = implode(",",$username);
$data = json_decode(#file_get_contents('https://api.twitch.tv/kraken/streams?channel=' . $callAPI), true);
foreach ($data['streams'] as $streams){
$name = $streams['channel']['name'];
echo $name.'<br>';
}
?>
I don't see the problem, if you just use array_diff, you can filter out the usernames.
$online = array();
foreach ($data['streams'] as $streams)
$online[] = $streams['channel']['name'];
$offline = array_diff($username, $online);
echo 'Online users: ' . implode(', ', $online) . "\n<br>";
echo 'Offline users: '. implode(', ', $offline);
Output (at time of writing):
Online users: sariett_siel, mufflermankr
Offline users: zeromi, aerosgw, krylen, tshirt_aion, snooky_aion, vashiro, papa456, vinley_aion, hanfkrokette, wtfast_siel, neckofthewood, paraproc, aionnae, uhiwi, valorium, knighterrantry, soulune, relizex3, vinlockz, trevyn201, tiger529, xkegi, logsnsticks, meowform, uzuk3, kalzard01, squall_m, suyji, headpcgamer

How To Pull JSON Data Using PHP

I'm trying to create a very simple php script that can pull data from a JSON file (array?) and echo it to the page. Sadly, I'm a complete newbie when it comes to PHP.
My goal is to dump all IP addresses and the corresponding client version into an output like this...
"127.0.0.1" "/Satoshi:0.9.1/"
"127.0.0.2" "/Satoshi:0.9.0/"
"127.0.0.3" "/Satoshi:0.9.0/"
"127.0.0.4" "/Satoshi:0.9.1/"
I can get the code to dump all data, but I'm not sure how to pull the ip and version without the ip and client version being named.. If that even makes sense?
Here is the code. What do I need to make it dump the correct data?
<?php
$url = 'https://getaddr.bitnodes.io/nodes/1407675714.json';
$JSON = file_get_contents($url);
echo $JSON;
$data = json_decode($JSON);
var_dump($data);
?>
Thanks for your help!
Something like
<?php
$url = 'https://getaddr.bitnodes.io/nodes/1407675714.json';
$JSON = file_get_contents($url);
$data = json_decode($JSON);
$data = (array)$data; // cast from stdClass to array, as results have int keys
foreach($data['nodes'] as $results){
echo $results[0]. " ". $results[3]."<br />";
}
?>
It doesn't makes much sense to convert an array of hashes into the one of some non-named entities. I guess that all you need is to dump it in the following way:
foreach($data as $t)
{
echo("ip=".$t->ip." ua=".$t->ua);
}
I don't think there is any reason to cast to an array. Just process the returned object. This one has the double quotes as requested as well.
<?php
$url = 'https://getaddr.bitnodes.io/nodes/1407675714.json';
$json = file_get_contents($url);
$data = json_decode($json);
foreach($data->nodes as $results){
echo "\"".$results[0]."\" \"".$results[3]."\"<br />";
}
?>

Categories