0

Why I'm not able to parse csv files (or equivalently open them) using WordPress shortcode?

Problem: I wish to use a shortcode to Parse Contents of a csv file and display its contents effectively. But the problem is that for some reason, the file doesn't opens/shows up despite different turn arounds. The server logs say that the GET request to the file was successful.

My Shortcode:

function wpb_demo_shortcode() { 
    if (($open = fopen("http://localhost:8000/a.csv", "r")) !== FALSE) 
  {
  
    while (($data = fgetcsv($open, 1000, ",")) !== FALSE) 
    {        
      $array[] = $data; 
    }
  
    fclose($open);
  }
  echo "<pre>";
  //To display array data
  var_dump($array);
  echo "</pre>";
}
add_shortcode('website-url-name', 'wpb_demo_shortcode');

There are similar questions around: Why is file_get_contents returning page source?

Again the solution returns no different. It's showing a blank pop up for me. I don't even know what's the problem with WordPress because regular plain PHP script is able to render it successfully.

Kindly enlighten the mistake here.

EDIT: I just found that instead of using localhost:8000, I used https://pippinsplugins.com/edd-api/products and it works like a magic. I don't know why it is not able to get files files from my localhost. Very weird.

some ss regarding shortcode being called and output.

3
  • 1
    So you tried wp_remote_get() and it really didn't work? Have you confirmed the request actually responded with a valid CSV file/data? And you mentioned "blank pop up" - what pop up? How did you call your shortcode? Also, $array should be defined before adding items to that array.. And note that shortcodes must always return the output and not echo anything because doing so can break many things, e.g. it will invalidate REST API's JSON responses.
    – Sally CJ
    Jun 5, 2022 at 18:16
  • @SallyCJ Yes, GET requests to server are successful for localhost:8000 from Server Logs. Also, everything regarding $array and all are perfectly setup because it responds well to other website (link given in question) and it doesn't works same when I replace the website to localhost:8000/a.json, where both json files are same too. Jun 5, 2022 at 18:37
  • "from Server Logs" - how about, for testing, try var_dump( wp_remote_retrieve_body( wp_remote_get( 'http://localhost:8000/a.csv' ) ) ) ? Does it output a valid CSV string? If all else fails, try moving the file to somewhere else, change its permissions, etc..
    – Sally CJ
    Jun 5, 2022 at 19:15

0

Your Answer

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

Browse other questions tagged or ask your own question.