1

I'm trying to write a shortcode in my theme's functions.php file that can display the contents of a CSV file on our server.

I'll worry about reading the CSV file into arrays and such later, but for now I just want to make sure I can read a file's contents using file_get_contents. However, when I run the shortcode below, the alert contains HTML.

function display_csv_data_func( $atts ) {
   $file_contents = file_get_contents("http://example.com/something/file.csv");
   return "<script>alert('" . $file_contents . "');</script>";
}
add_shortcode( 'display_csv_data', 'display_csv_data_func' );

returns:

alert('
<!doctype html>
<!--[if lt IE 7 ]> <html class="no-js ie6" lang="en-US"
...

Is there something about shortcodes, functions.php or WordPress in general that's interfering with my code? Seems like this should be a fairly simple thing to do...

6
  • It'd be helpful to see the contents of the HTML that's being returned.
    – Aaron
    Mar 4, 2017 at 23:40
  • My 1st guess is that the HTML that you're getting is a 404 (or other error) page from example.com. That is, are you sure the URL in your file_get_contents() call is correct? If you enter that URL in a browser, do you get the .csv file or something else? Mar 4, 2017 at 23:46
  • @Aaron The HTML is pretty lengthy, what are you looking for specifically?
    – jeffbeene
    Mar 4, 2017 at 23:51
  • @Paul'SparrowHawk'Biron I'm positive that the URL is correct, as I can navigate to it and fopen is also successful.
    – jeffbeene
    Mar 4, 2017 at 23:52
  • Does wp_remote_get() work?
    – moraleida
    Mar 5, 2017 at 0:17

1 Answer 1

1

Aha, I figured it out! You have to use wp_remote_get(). I'm not exactly sure why at this point, but here's what the code looks like:

function display_csv_data_func( $atts ) {
   $file_path = "http://example.com/something/file.csv";
   $response = wp_remote_get($file_path);
   $response_body = wp_remote_retrieve_body($response);
   return "<script>alert('" . $response_body . "');</script>";
}
add_shortcode( 'display_csv_data', 'display_csv_data_func' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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