Skip to content

Instantly share code, notes, and snippets.

@ryanmr

ryanmr/weather.php

Created Aug 25, 2015
Embed
What would you like to do?
<?php
$url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20woeid%3D12781740&format=json&diagnostics=true&callback=";
// $url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20text%3D%22Macalester%20-%20Groveland%2C%20MN%22&format=json&diagnostics=true&callback=";
// $url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.places%20where%20woeid%3D29306623&format=json&diagnostics=true&callback=";
$text = file_get_contents($url);
$data = json_decode($text, true);
function get_location($data) {
$d = $data['query']['results']['place'];
$r = [];
// specificity descending
$keys = ['locality2', 'locality1', 'admin3', 'admin2', 'admin1', 'country'];
foreach ($keys as $key) {
if (isset($d[$key])) {
$r[] = $d[$key]['content'];
}
}
return $r;
}
$location = get_location($data);
var_dump($location);
echo join($location, ", ");
/*
array(4) {
[0]=>
string(10) "Vestamager"
[1]=>
string(10) "Copenhagen"
[2]=>
string(11) "Hovedstaden"
[3]=>
string(7) "Denmark"
}
Vestamager, Copenhagen, Hovedstaden, Denmark
*/
/*
array(5) {
[0]=>
string(22) "Macalester - Groveland"
[1]=>
string(8) "St. Paul"
[2]=>
string(6) "Ramsey"
[3]=>
string(9) "Minnesota"
[4]=>
string(13) "United States"
}
Macalester - Groveland, St. Paul, Ramsey, Minnesota, United States
*/
/*
array(4) {
[0]=>
string(8) "St. Paul"
[1]=>
string(6) "Ramsey"
[2]=>
string(9) "Minnesota"
[3]=>
string(13) "United States"
}
St. Paul, Ramsey, Minnesota, United States
*/
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment