0

Note: This is cross-posted on stackoverflow.

I need to get some XSQL generated XML data from a remote server, process it, and display it on a GoDaddy Managed WordPress page. (This is the website my workplace has to use for various reasons.) Currently, the data goes into a Google Sheet that's displayed in an iframe, but this is not a viable long-term solution.

The URL for the remote server contains the search calls for the XSQL database, including dates. The data is fire weather related, so passing the correct dates for observations and forecasts are necessary. I don't have an issue with making the URL in either PHP or JavaScript - getting the date, making the correct string from it, and injecting it into the URL.

Is there a way to do this given the restriction of the GoDaddy Managed WordPress environment and that we're not likely to talk the people who pay for the hosting into buying plugins?

I have looked at using JavaScript to fetch() the data, but doesn't work because of CORS, and using 'no-cors' returns an opaque object. Basically, it tells me "yes, there's a thing there." Naturally, not using 'no-cors' returns an error.

I have looked at PHP, but I don't understand how to make PHP work in the environment I'm given.

I am "learning" JavaScript and PHP piecemeal - a very old and unused background in one C class in college has served me well, as have Google and DuckDuckGo - so I'm very, very new to these codes.

Is there a way to create WordPress hooks to do what I want to do? I've been trying to wrap my brain around them, but not been very successful.

Note: the code below has had some information stripped and put in <>. It should still be obvious what's going on.

Failed JS Pull Method:

function getTodaysDate() {
    var m_names = new Array("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC");
    var d = new Date();
    var curr_date = d.getDate().toString();
    if (curr_date.length == 1) {
        curr_date = `0${curr_date}`;
    }
    var curr_month = d.getMonth();
    var year = d.getFullYear();
    var curr_year = year.toString().substr(2.2);
    var today = `${curr_date}-${m_names[curr_month]}-${curr_year}`;
    return today;
}

function getYesterday() {
    var m_names = new Array("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC");
    var d = new Date(new Date().setDate(new Date().getDate()-1));
    var last_date = d.getDate().toString();
    if (last_date.length == 1) {
        last_date = `0${last_date}`;
    }
    var last_month = d.getMonth();
    var year = d.getFullYear();
    var last_year = year.toString().substr(2.2);
    var yesterday = `${last_date}-${m_names[last_month]}-${last_year}`;
    return yesterday;
}
        
async function locWx() {
    var urlDate= getYesterday();
    var locUrl= `https://<sanitized site and directories>/<filename>.xsql?stn=&sig=LOC&type=&start=${urlDate}&end=${urlDate}&time=&priority=&fmodel=&sort=&ndays=&user=`;
    console.log(locUrl);
    var Res= fetch(locUrl);
    var response= await Res;
    var xmlText= await response.text();
    return xmlText;
    console.log(xmlText);

/*fetch(locUrl, {mode: 'no-cors'})
    .then(response => {
        if(!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.text();
    })
    .then(xmlText => {
        const parser = newDOMParser();
        const xmlDoc = parser.parseFromString(xmlText, 'text/xml');
        consle.log(xmlDoc);
    })
    .catch(error => {
        console.error('There was a problem with the fetch operation:', error);
        console.log(alfUrl);
    })*/
}

Failed jQuery Method:

        $(document).ready(function(){
            var m_names = new Array("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC");
            var d = new Date(new Date().setDate(new Date().getDate()-1));
            var last_date = d.getDate().toString();
            if (last_date.length == 1) {
                last_date = `0${last_date}`;
            }
            var last_month = d.getMonth();
            var year = d.getFullYear();
            var last_year = year.toString().substr(2.2);
            var yesterday = `${last_date}-${m_names[last_month]}-${last_year}`;
            var locUrl = `https://<sanitized site and directories>/<filename>.xsql?stn=&sig=LOC&type=&start=${yesterday}&end=${yesterday}&time=&priority=&fmodel=&sort=&ndays=&user=`;
            console.log(locUrl);
            $.ajax({
                type: "GET",
                mode: "no-cors",
                url: locUrl,
                dataType: "html",
                success: function(xml){
                    console.log("here");$
                        $(xml).find('row').each(function(){
                            var number = $(this).find('firstField').text();
                            var name = $(this).find('secondField').text();
                            var lat = $(this).find('thirdField').text();
                            $('<tr></tr>').html('<th>' +number+ '</th><td>' +name+ '</td><td>' +lat+ '</td>').appendTo('#myTable');
                        });
                }
            });
        });

I have to research PHP again. I can't find where I had an attempt at the code since I don't have a good testing environment. (I'll keep looking for one.)

9
  • I'm not clear: you can't add custom plugins, but you can customise the theme and write PHP there? That's almost the same thing - you can add hooks from the theme's functions.php, yes - except I suppose if the theme code doesn't get loaded for WordPress REST API requests (I'm not sure)
    – Rup
    Commented Jun 13 at 10:14
  • At first glance from the GoDaddy plans page and support pages there are no restrictions uploading your own plugins (?). You're just banned from using a list they've blocked.
    – Rup
    Commented Jun 13 at 10:27
  • are you asking how to make the request to the remote server? Or have you figured that out but don't know how to process the result? There's too much stuff being asked here and no code to work with, and the fact that your site is hosted on managed WP shouldn't impact the question at all (you also can't ask for plugin recommendations here so don't worry about that, anyone who answers with a plugin would get downvoted or converted into a comment anyway). Can you break this question apart and subdivide it? And include any code that's relevant?
    – Tom J Nowell
    Commented Jun 13 at 10:34
  • D'oh I misread 'buying plugins' as 'paying for a higher hosting tier that supports plugins'. Yes if you can write a plugin you can do this all yourself e.g. make a REST API endpoint on your server that assembles and makes the XML request, caches the result in a transient and then returns the data to your web page to display.
    – Rup
    Commented Jun 13 at 11:04
  • @TomJNowell I'll update with code soon, but I think I only have the JS since I don't have a PHP testing environment. I'll see what I can come up with. The main thing is knowing how to implement it once I come up with it. Commented Jun 13 at 12:34

1 Answer 1

1

Step-by-Step Guide to Create a WordPress Plugin for Fetching and Displaying Remote XML Data

1. Create a New Plugin Directory

  • Connect to your WordPress installation via FTP or use the file manager in your hosting control panel.
  • Navigate to wp-content/plugins/.
  • Create a new directory named remote-xml-fetch.

2. Create the Plugin File

  • Inside the remote-xml-fetch directory, create a new file named remote-xml-fetch.php.

3. Add Plugin Header

  • Open remote-xml-fetch.php in a text editor and add the following plugin header:
<?php
/**
 * Plugin Name: Remote XML Fetch and Display
 * Description: Fetches remote XML data and displays it on a WordPress page.
 * Version: 1.0
 * Author: Your Name
 */

4. Add Function to Fetch XML Data

  • Below the plugin header, add the following PHP function to fetch and process the XML data:
function fetch_remote_xml_data() {
    $yesterday = date('d-M-y', strtotime('-1 day'));
    $url = "https://<sanitized site and directories>/<filename>.xsql?stn=&sig=LOC&type=&start={$yesterday}&end={$yesterday}&time=&priority=&fmodel=&sort=&ndays=&user=";

    $response = wp_remote_get($url);

    if ( is_wp_error($response) ) {
        return 'Failed to fetch data.';
    }

    $body = wp_remote_retrieve_body($response);

    if ( empty($body) ) {
        return 'No data retrieved.';
    }

    $xml = simplexml_load_string($body);

    if ( $xml === false ) {
        return 'Failed to parse XML.';
    }

    // Process and display the XML data
    $output = '<table id="myTable"><tr><th>Number</th><th>Name</th><th>Latitude</th></tr>';
    foreach ( $xml->row as $row ) {
        $number = $row->firstField;
        $name = $row->secondField;
        $lat = $row->thirdField;
        $output .= "<tr><th>{$number}</th><td>{$name}</td><td>{$lat}</td></tr>";
    }
    $output .= '</table>';

    return $output;
}

5. Create a Shortcode to Display the Data

  • Add the following function to create a shortcode that displays the fetched XML data:
function display_remote_xml_data() {
    return fetch_remote_xml_data();
}
add_shortcode('display_xml_data', 'display_remote_xml_data');

6. Save and Upload the Plugin File

  • Save the changes to remote-xml-fetch.php.
  • Upload the remote-xml-fetch.php file to the remote-xml-fetch directory on your WordPress server if you edited it locally.

7. Activate the Plugin

  • Log in to your WordPress admin dashboard.
  • Navigate to Plugins.
  • Find Remote XML Fetch and Display in the list and click Activate.

8. Use the Shortcode in a Post or Page

  • Edit the post or page where you want to display the XML data.
  • Add the following shortcode where you want the data to appear:
[display_xml_data]

9. Verify the Output

  • View the post or page to ensure the XML data is fetched and displayed correctly in a table.
2
  • 1
    I'd probably 1) store the fetched data in a transient rather than reload for every request 2) serve it from the REST API rather than a shortcode because that fits in with OP's existing code better.
    – Rup
    Commented Jun 14 at 8:34
  • Thanks, but that's a different perspective.
    – mukto90
    Commented Jun 14 at 13:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.