I'm working with an API from underground weather. I'm trying to put some values into my website on localhost. I include a lot of values without problem. Like:
Temperature: 30°F
Wind: Fast
Here is the json of those values:
"current_observation": {
"image": {
"url":"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",
"title":"Weather Underground",
"link":"http://www.wunderground.com"
},
"display_location": {
"full":"Buenos Aires, Argentina",
"city":"Buenos Aires",
"state":"",
"state_name":"Argentina",
"country":"AG",
"country_iso3166":"AR",
"zip":"00000",
"magic":"1",
"wmo":"87582",
"latitude":"-34.56999969",
"longitude":"-58.41999817",
"elevation":"6.00000000"
},
"observation_location": {
"full":"Palermo, Buenos Aires, Ciudad Autónoma de Buenos Aires",
"city":"Palermo, Buenos Aires",
"state":"Ciudad Autónoma de Buenos Aires",
"country":"Argentina",
"country_iso3166":"AR",
"latitude":"-34.595318",
"longitude":"-58.419781",
"elevation":"124 ft"
},
"estimated": {
},
"station_id":"IBUENOSA157",
"observation_time":"Last Updated on April 26, 7:52 PM ART",
"observation_time_rfc822":"Sat, 26 Apr 2014 19:52:51 -0300",
"observation_epoch":"1398552771",
"local_time_rfc822":"Sat, 26 Apr 2014 19:52:52 -0300",
"local_epoch":"1398552772",
"local_tz_short":"ART",
"local_tz_long":"America/Buenos_Aires",
"local_tz_offset":"-0300",
"weather":"Clear",
"temperature_string":"65.8 F (18.8 C)",
"temp_f":65.8,
"temp_c":18.8,
"relative_humidity":"63%",
and in the index php file:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/f84c5a4cd54b3216/geolookup/alerts/astronomy/almanac/conditions/forecast/hourly/q/autoip.json");
$parsed_json = json_decode($json_string);
$temp_c = $parsed_json->{'current_observation'}->{'temp_c'};
echo "{$'temp_c'};
That displays the temperature. The temperature in the json code is in: Current_observation and then the value temp_c.
The problem is that I want to echo the forecast, and the forecast is in a different location than the temp_c.
For example. I want to echo the current conditions, that is here:
The problem is, that is in:
{'forecast'}->{'simpleforecast'}->{'forecastday'} and then there is a zero for the current day, a 1 for the next day, a 2 for the following day, and a 3 for the next to the next day.
When I try to do that in php:
{'forecast'}->{'simpleforecast'}->{'forecastday'}->{'0'}->{'conditions'};
It does not show anything. How I can go into a value json when in the array there is a 0?
PD: for 0, there is one condition, for 1 (that is next day) there is other condition, and like that the others day. Thanks
For me it just works fine, I just tested your code, I just modified it a little bit:
<?php
$json_string = file_get_contents("http://api.wunderground.com/api/f84c5a4cd54b3216/geolookup/alerts/astronomy/almanac/conditions/forecast/hourly/q/autoip.json");
$parsed_json = json_decode($json_string, true);
$desired_forecast = $parsed_json['forecast']['simpleforecast']['forecastday'][0]['conditions'];
echo '<pre>';
print_r($desired_forecast); // Thunderstorm
echo '</pre>';
It is accessible.
You were really close but {'0'} means there is an object with the key 0, while you really wanted to access the first index of forecastday
var_dump($parsed_json->{'forecast'}->{'simpleforecast'}->{'forecastday'}[0]->conditions);
Related
How would I decode this JSON data to get the Location link of the event? NOTE: When I say Location I don't mean the field "location" in the json data, I am referring to the field which is in "customFields", then has a "value" which is a link to Google Maps, it also has the "type" = 9.
Problem: I am currently stuck with a page which looks like the image below, the "Notice: Undefined offset: # in...." error continues for 200 lines, because the JSON file contains the data of 200 events, the JSON included only contains the first event.
Desired Result: For the link to google maps page to be echoed on every line. I think the solution is very simple, just changing my Source code (Included) so that it can read the JSON file.
JSON dataset:
[{"eventID":152913573,"template":"Brisbane City Council","title":"Clock Tower Tour","description":"The Clock Tour Tower is a ‘must-do’ for anyone and everyone in Brisbane!<br /> <br /> For many years, City Hall’s Clock Tower made the building the tallest in Brisbane, offering visitors a magnificent 360 degree view of the city around them. Whilst the view has changed significantly over the last 90 years, the time-honoured tradition of “taking a trip up the tower” happily continues at Museum of Brisbane.<br /> <br /> The Clock Tower Tour includes a ride in one of Brisbane’s oldest working cage lifts, a look behind Australia’s largest analogue clock faces and time to explore the observation platform that shares a unique perspective of the city. See if you can catch a glimpse of the bells!<br /> <br /> <strong>Location</strong>: Tour begins from Museum of Brisbane reception on Level 3 of City Hall.","location":"Museum of Brisbane, Brisbane City","webLink":"","startDateTime":"2021-06-13T00:00:00","endDateTime":"2021-06-14T00:00:00","dateTimeFormatted":"Sunday, June 13, 2021","allDay":true,"startTimeZoneOffset":"+1000","endTimeZoneOffset":"+1000","canceled":false,"openSignUp":false,"reservationFull":false,"pastDeadline":false,"requiresPayment":false,"refundsAllowed":false,"waitingListAvailable":false,"signUpUrl":"https://eventactions.com/eareg.aspx?ea=Rsvp&invite=0tva7etjn38te1bve2yj59425pupt7wvscmr1z6depcj9ctnrh7r","repeatingRegistration":0,"repeats":"Every Sunday, Tuesday, Wednesday, Thursday, Friday and Saturday through June 30, 2021","seriesID":152913560,"eventImage":{"url":"https://www.trumba.com/i/DgDhxtvzZEBEz%2AjAEUDofPUE.jpeg","size":{"width":1290,"height":775}},"detailImage":{"url":"https://www.trumba.com/i/DgDhxtvzZEBEz%2AjAEUDofPUE.jpeg","size":{"width":1290,"height":775}},"customFields":[{"fieldID":22503,"label":"Venue","value":"Museum of Brisbane, Brisbane City","type":17},{"fieldID":22505,"label":"Venue address","value":"Museum of Brisbane, Brisbane City Hall, 64 Adelaide Street, Brisbane City","type":9},{"fieldID":21859,"label":"Event type","value":"Family events, Free","type":17},{"fieldID":22177,"label":"Cost","value":"Free","type":0},{"fieldID":23562,"label":"Age","value":"Suitable for all ages","type":0},{"fieldID":22732,"label":"Bookings","value":"Book via the Museum of Brisbane website.","type":1},{"fieldID":51540,"label":"Bookings required","value":"Yes","type":3}],"permaLinkUrl":"https://www.brisbane.qld.gov.au/trumba?trumbaEmbed=view%3devent%26eventid%3d152913573","eventActionUrl":"https://eventactions.com/eventactions/brisbane-city-council#/actions/cvuzsak1g2d45mndcjwkp24nfw","categoryCalendar":"Brisbane's calendar|Museum of Brisbane","registrationTransferTargetCount":0,"regAllowChanges":true}]
Code so far:
<?php
$output = file_get_contents("Events.json");
$decode = json_decode($output, true);
for($i = 0; $i < count($decode); $i++) {
if($decode[$i]['customFields'][$i]['type'] == 9){
echo $decode[$i]['customFields'][$i]['label'][$i]['value'];
}
echo "<br>";
}
?>
You're using the $i loop counter twice in the same expression, but the second time you use it it's pointing at non-existent elements. The snippet below 1) treats JSON objects as objects (I find it less confusing when matching code to data), and 2) uses foreach to iterate over the arrays.
I've also extracted the latitude and longitude for you into $latlong
Try this:
$decode = json_decode($json);
foreach ($decode as $event) {
foreach ($event->customFields as $field) {
if ($field->type == 9) {
echo $field->value."\n";
if (preg_match('/href="(.*?)"/', $field->value, $matches)){
preg_match('/q=([\-\.0-9]*),([\-\.0-9]*)/',$matches[1], $latlong);
array_shift($latlong);
var_dump($latlong);
}
break;
}
}
}
Output
Museum of Brisbane, Brisbane City Hall, 64 Adelaide Street, Brisbane City
array(2) {
[0]=>
string(11) "-27.4693454"
[1]=>
string(11) "153.0216909"
}
Demo:https://3v4l.org/AkRvI
how to convert HTML data to json, example as below, description content how to convert as json, it is from mysql, php., how to send json responce as plain text, but description comes from the mysql db as it is, but how to send the json responce api to androind.
public function actionTestanalysis()
{
//echo $keyword=$_POST['keyword'];
$query= Yii::app()->db->createCommand("select * from test ORDER BY id DESC")->queryAll();
$arr = array();
if(count($query) > 0) {
foreach($query as $query){
$arr[] = $query;
}
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;
//exit;
}
json responce
[
{
"id": "99",
"name": "Max-Gain on or before 25th January 2016 in Max India Limited.",
"description": "
\r\n\tMax India Limited has announced the Record date for Three way De-Merger as 28th January 2016 (Thursday). <\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tAnyone want to Gain from the three way De-Merger of Max India Group one should buy the shares of Max India Limited on or before – 25th January 2016 (Cum-Date – Monday Tentavily) otherwise to be on safer side you can buy on or before 22nd January 2016(Friday) and get invested in it.<\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tIf any investor invests for a period Of 12 – 18 Months , this scrip will be a Multifold - Multi Bagger.<\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tTo View the full report on Max India Limited authored . <\/div>\r\n
\r\n\t <\/div>\r\n
\r\n\tPlease Click The Below Link<\/div>\r\n
\r\n\t
\r\n\t\thttp:\/\/www.test.com\/index.php\/newsOpportunities\/list\/scroll\/no-pain-all-gain-maximum-benefit-in-max-india-ltd<\/a><\/p>\r\n<\/div>\r\n",
"image": "",
"status": "unlock"
},
You have also one error in the cycle in your code.
Try this:
if (count($query) > 0) {
foreach ($query as $queryElement) {
$el = $queryElement;
$el['description'] = trim(preg_replace('/\s+/', ' ', strip_tags($el['description'])));
$arr[] = $el;
}
}
Try before: echo $json_response set header content type to application/json
<?PHP
header('Content-Type: application/json');
echo $json_response;
Use htmlentities() instead of strip_tags(), in order to retain actual content stored in db.
I am parsing the below json in php
{
"responseHeader":{
"status":0,
"QTime":22,
"params":{
"fl":"title,id",
"indent":"true",
"q":"einstein",
"hl.simple.pre":"<em>",
"hl.simple.post":"</em>",
"wt":"json",
"hl":"true",
"rows":"3"}},
"response":{"numFound":63,"start":0,"docs":[
{
"id":"1",
"title":"Albert Einstein"},
{
"id":"2088",
"title":"Nationalism"},
{
"id":"1551",
"title":"Dean Koontz"}]
},
"highlighting":{
"1":{
"text":[" for school exam September The Collected Papers of Albert <em>Einstein</em> Vol Doc s Unthinking for authority"]},
"2088":{
"text":[" in a letter to Alfred Kneser June Doc in The Collected Papers of Albert <em>Einstein</em> Vol Nationalism"]},
"1551":{
"text":[" changes since meeting Travis Did you get the leash on him yet <em>Einstein</em> Part Chapter Nora s query during"]}}}
using json_decode and looping through the result array I could get the individual elements in the docs section,
foreach ($myArray['response']['docs'] as $doc) {
echo $doc['id'] . "<br/>";
echo $doc['title'] . "<br/>";
}
I am now trying to figure out in getting the values from the highlighting section of this json. I want to get the text fields in the highlighting part and store it in a array.
"highlighting":{
"1":{
"text":[" for school exam September The Collected Papers of Albert <em>Einstein</em> Vol Doc s Unthinking for authority"]},
"2088":{
"text":[" in a letter to Alfred Kneser June Doc in The Collected Papers of Albert <em>Einstein</em> Vol Nationalism"]},
"1551":{
"text":[" changes since meeting Travis Did you get the leash on him yet <em>Einstein</em> Part Chapter Nora s query during"]}}}
The array should be like this,
"1" => " for school exam September The Collected Papers of Albert <em>Einstein</em> Vol Doc s Unthinking for authority"
"2088" => " in a letter to Alfred Kneser June Doc in The Collected Papers of Albert <em>Einstein</em> Vol Nationalism"
How to achieve this? Is there any way to map the id element of the docs to the number specified in the highlighting part?
You may try this (Example)
$myArray = json_decode($json, true);
$highlighting = array();
foreach($myArray['highlighting'] as $key => $value)
{
$highlighting[$key] = $value['text'][0];
}
Result :
Array (
[1] => for school exam September...
[2088] => in a letter to Alfred ...
[1551] => changes since meeting ...
)
I am trying to grab my twitter feed using the following code:
// Make the request and get the response into the $json variable
$json = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
// It's json, so decode it into an array
$result = json_decode($json);
// Access the profile_image_url element in the array
echo $result->created_at;
?>
I get the result of:
Thu Oct 25 18:40:50 +0000 2012
If I try to get the text with:
echo $result->text;
I get this error:
Notice: Undefined property: stdClass::$text in /Library/WebServer/Documents/include/twitter_noformat/items.php on line 35
A partial var_dump of my data format includes this:
{"created_at":"Thu Aug 01 16:12:18 +0000 2013",
"id":362969042497175553,
"id_str":"362969042497175553",
"text":"A warm welcome to our new international students from China, Hong Kong and Germany! http:\/\/t.co\/GLvt3GynJV",
"source":"web",
"truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":
My question is:
created_at gives me a value. id gives me a value. Why doesn't text? I know nothing about JSON btw. I'm not a very advanced programmer, but the pattern looks the same to me.
Edit: Well I found a cool snippet that converted my twitter array to something more readable. The function goes like this:
// It's json, so decode it into an array
$result = json_decode($json);
// Access the profile_image_url element in the array
$pretty = function($v='',$c=" ",$in=-1,$k=null)use(&$pretty){$r='';if(in_array(gettype($v),array('object','array'))){$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").'<br>';foreach($v as $sk=>$vl){$r.=$pretty($vl,$c,$in+1,$sk).'<br>';}}else{$r.=($in!=-1?str_repeat($c,$in):'').(is_null($k)?'':"$k: ").(is_null($v)?'<NULL>':"<strong>$v</strong>");}return$r;};
echo $pretty($result);
The results now look like this:
statuses_count: 583
lang: en
status:
created_at: Thu Aug 01 21:10:10 +0000 2013
id: 363044004444651522
id_str: 363044004444651522
text: #CalStateEastBay AD Sara Lillevand Judd '86 honored for her work as an athletic adminstrator. http://t.co/WzOqjIDrBw
This is strange because that makes text look like it's part of an object?
I have determined that twitter kicks back an array of objects. Those objects can have a lot of items(?) As I mentioned previously though I can echo $result->created_at; but not text. They are both at the same level of the array.
thanks in advance for your help,
Donovan
Alright here was my solution after a day of research:
$result = json_decode( $json );
echo "Text:" . $result->status->text . "<br />";
Text was a child(?) of status. I could echo created_at because it was used at two levels of the array, which I hadn't seen before. Text was inside the status object I guess.
created_at: Thu Oct 25 18:40:50 +0000 2012
favourites_count: 1
utc_offset: -25200
time_zone: Pacific Time (US & Canada)
geo_enabled: 1
verified:
statuses_count: 583
lang: en
status:
created_at: Thu Aug 01 21:10:10 +0000 2013
id: 363044004444651522
id_str: 363044004444651522
text: #CalStateEastBay AD Sara Lillevand Judd '86 honored for her work as an athletic adminstrator. http://t.co/WzOqjIDrBw
Here is a snippet from yahoo Weather showing the identical tags
<yweather:forecast day="Mon" date="16 Jan 2012" low="-1" high="6" text="Clear" code="31"/>
<yweather:forecast day="Tue" date="17 Jan 2012" low="3" high="7" text="Mostly Sunny" code="34"/>
To access the day in the first tag I use the following function:
function get_forecast_day(SimpleXMLElement $xml) {
// Pull forecast day
$forecast['day'] = $xml->channel->item->children('yweather', TRUE)->forecast->attributes()->day;
echo $forecast['day'] . ", ";
return $day;
}
Any ideas how I can access the day in the second tag. Obviously searching for the value "Tue" is no good as these values will change daily.
Thanks in advance.
->forecast can be used as array, so go for second element with index 1:
$xml->channel->item->children('yweather', TRUE)->forecast[1]->attributes()->day