Updating the Temperature and Air Quality API calls

I was finding that any page loads of the Temperature and Air Quality pages were taking a long time, and sometimes timed out without retrieving the data.

To get the sensor data for the pages, I make an API call to the sensor.community site to download a small JSON file, and then parse out the figures I need.

I was using a php file_get_contents call to download the JSON, but then I came across documentation that suggested changing to the wp_remote_get instead. I’ll not attempt to give a tutorial on the differences between the two, because I don’t really understand it. But I changed the code from:

$jsonFile = file_get_contents("https://data.sensor.community/airrohr/v1/sensor/42633/");

to:

$response = wp_remote_get("https://data.sensor.community/airrohr/v1/sensor/42633/");
if ( is_wp_error( $response ) || ( wp_remote_retrieve_response_code( $response ) != 200 ) ) {
	echo 'Something went wrong';
}
$jsonFile = wp_remote_retrieve_body( $response );

and a call that used to take 20-30 seconds to respond now takes 2-3 seconds instead.

Leave a Reply

Your email address will not be published. Required fields are marked *