Skip to content

Instantly share code, notes, and snippets.

What would you like to do? API to PHP Associative Array
# Note: This is not secure! If you somehow get malicious code back from, this can run arbitrary code. Use wisely and sanitize your inputs!
# 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 '<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
$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