So take this code:
$bizt_a = json_decode(file_get_contents("https://karteritesed.hu/biztositok.json"));
Separate it out so that we do 1 thing per line ( if you pass it straight into json_decode
what happens if the request fails and that site is down? json_decode
isn't expecting an error message! It's going to turn around and ask "What's this?!" )
$json = file_get_contents("https://karteritesed.hu/biztositok.json");
$bizt_a = json_decode( $json );
Now that each line does 1 thing and only 1 thing, we can ignore the json decoding part, and focus on fetching the contents of that URL.
Lets look up the examples at https://developer.wordpress.org/reference/functions/wp_remote_get/
It wants the URL as the first parameter, and the second parameter is where we can give it any additional options. I don't think you need additional options so we can leave that out
$response = wp_remote_get( 'URL goes here...' );
$response
is an array that has the content of the URL, and other things, such as the headers, the response code etc. Afterall don't you want to check it worked? What if it was a 404 not found!!!
So lets do a quick check, remember HTTP 200 means OK 👍🏻 great everything worked:
if ( is_wp_error( $response ) || ( wp_remote_retrieve_response_code( $response ) != 200 ) ) {
// something went wrong!!! Abort!!!
}
Then we can extract the text:
$responseBody = wp_remote_retrieve_body( $response );
And JSON decode it:
$bizt_a = json_decode( $responseBody );
Then you can continue like you did before.
Even better, swap wp_remote_get
for wp_safe_remote_get
for added protection.
https://developer.wordpress.org/reference/functions/wp_safe_remote_get/
Note though, that making a request to another server is expensive!! You don't want to do this on every page load or your site will get slow. It also means your site will always be as slow or slower than karteritesed.hu
because it has to grab that file. Save that JSON somewhere, maybe in a cache etc and things will run faster
esc_attr
andesc_html
, that JSON might sneak some HTML or script tags!