Last active
November 30, 2017 03:49
-
-
Save JohnMertz/487eb45dd8c982093e30143de027b685 to your computer and use it in GitHub Desktop.
Darksky.net API to PHP Associative Array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#/bin/bash | |
# Note: This is not secure! If you somehow get malicious code back from Darksky.net, this can run arbitrary code. Use wisely and sanitize your inputs! https://www.xkcd.com/327/ | |
output="yourOutputPathHere.php" | |
# Replace with your API key and coordinates. Should be fine with other units and may work without excluding minutel and flags. | |
# I have only teste this format (hourly and daily with SI units). This works for Ottawa, Canada. | |
# Pipes force into separate lines with quoted fields in PHP associative array format: "attribute_name1"=>"value","attribute_name2"=>... | |
# Outputs to a .tmp of your defined file name. | |
curl --compress 'https://api.darksky.net/forecast/<api_key_here>/45.421,-75.69?units=si&exclude=minutely,flags' | tr '{' '\n' | sed 's/},$//' | sed 's/,\ /\ /' | sed -r 's/([^"]),"/\1","/g' | sed -r 's/":([^"])/":"\1/g' | sed -r 's/([^"])\}/\1"\n/' | grep '^"time"' | sed 's/":"/"=>"/g' > $output.tmp | |
# Add preliminary PHP array definition and formatting to final output file | |
echo '<?php | |
$daily=array(); | |
$hourly=array();' > $output | |
# Add current and hourly (line 1-50; line 2 is the start of this hour, ie. 0-59min ago, so is probably best skipped by whatever uses this data) and today and daily (last 8 lines). | |
# Add array definition formatting and output. | |
head -n 50 /var/www/html/weather/darksky.tmp | sed 's/^/hourly[]=array(/' | sed -r 's/([^"])}?$/\1"/' | sed 's/$/);/' >> /var/www/html/weather/weather_data.php | |
tail -n 8 /var/www/html/weather/darksky.tmp | sed 's/^/daily[]=array(/' | sed -r 's/([^"])}?$/\1"/' | sed 's/$/);/' >> /var/www/html/weather/weather_data.php | |
echo '?>' >> /var/www/html/weather/weather_data.php | |
# Clean up unnecessary tmp file. This script overwrites the the output file, so it can appropriately be run from a cronjob automatically. | |
rm $output.tmp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment