Question is that is this correct code for wordpress site? When I tried it as a plugin the code broke my site with “redirect err”. What might be the problem officer?
<?php
/*
Plugin Name: External API XML to JSON
Plugin URI: http://erikilonen.com/
Description: Fetch XML from an external API and convert it to JSON.
Version: 1.0
Author: Erik Ilonen
Author URI: http://erikilonen.com/
*/
add_action('rest_api_init', function () {
register_rest_route('external-api/v1', '/test/', array(
'methods' => 'GET',
'callback' => 'fetch_external_api_data',
));
});
function fetch_external_api_data(WP_REST_Request $request) {
// Replace 'external_api_url' with the actual URL of the external API
$response = wp_remote_get('https://web-api.tp.entsoe.eu/api?securityToken=MY_TOKEN&documentType=A44&processType=A16&outBiddingZone_Domain=10YFI-1--------U&In_Domain=10YFI-1--------U&Out_Domain=10YFI-1--------U&periodStart=202403040800&periodEnd=202403040900');
if (is_wp_error($response)) {
return new WP_Error('fetch_error', 'Error fetching external API data', array('status' => 500));
}
$body = wp_remote_retrieve_body($response);
$xml = simplexml_load_string($body);
$json = json_encode($xml);
$data = json_decode($json, true); // Convert to associative array
return new WP_REST_Response($data, 200);
}
?>