Is there a simple example how to fetch JSON data from an external website (like for example http://openweathermap.org/current ) and parse one of the values (e.g. ‘temp’) so it would show up in my HTML?
I think using cURL/the Toolkit version is a better recommendation than using file_get_contents(). Also, file_get_contents() with an URL object as parameter requires allow_url_fopen to be enabled on your server.
I agree. file_get_contents is a trap for developers like @krl who end up using it without any error checking. If your API goes down it’ll return false and your entire page will break. Either apply correct error handling to this snippet (with a try catch) or use curl/toolkit.
At least the f::read() bit wouldn’t break your site. Your complete code is not safe, though, because you assume that you get back what you expect. For example, in case your API key is missing, your $json variable would give you
Array
(
[cod] => 401
[message] => Invalid API key. Please see http://openweathermap.org/faq#error401 for more info.
)
If this is the case
$listItems = ($test['list']);
would throw an error, because you $test variable doesn’t contain an index called list.
Nevertheless, suppressing errors makes your code hard to debug. Not a good idea.
OK. As i didn’t know how to implement the plugin solution with the remote class from the Kirby Toolkit i read a bit about cURL and this is my working php snippet now (my API code replaced by 12345). Is this save, or what would i have to do to make it save in case the source of the data is not available?
You’re checking for curl errors, which is good, but you’re still accepting the returned JSON data without verifying it.
If something goes wrong with the request (API down, key expired, place doesn’t exist, etc), $data will look like this:
{
"cod":401,
"message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."
}
If you try to access $data[‘main’] right now, you’ll throw an error. You should check the returned “cod” value to check if the request was successful before reading values from it.
Even if the returned code is correct, the data you get back may change and the $data index you are expecting doesn’t exist anymore, so you would have to check for that as well.
Just out of curiosity, now this has been solved - is there a way to do something similar, but with an RSS feed as the source rather than JSON? Can the toolkit help with getting the information in an external RSS feed on to the page in a Kirby site?
Awesome! So I can basically do the same as above, but change the $url variable to the url of an rss feed instead? Obviously i would need to change the rest to match the items in the feed.