0

I am trying to open a CSV file by using the JavaScript prompt function. So far I can successfully fetch the file name, however when I pass it to fopen() function in PHP to actually read the file, then it shows errors.

Please don't think that I just post this question. I read the previous question on StackOverflow, however, they don't work in my use case

CSV file name "data.csv"

Name, Class, Roll

zjvc,    11, 012
sahlk,   12, 154
jvcxj,   9,  145

<?php


echo "<script type='text/javascript'> let fid = prompt('Enter file name'); </script>";  // ask for file name

$file_name = "<script type='text/javascript'> document.write(fid); </script>"; // read data from prompt

$data_file = "$file_name.csv";

echo"$data_file";

$handle=fopen($data_file,'r');
$data = fgetcsv($handle,10000,",");
$all_record_arr = [];

while( ($data = fgetcsv($handle,10000, ",")) !== FALSE)
{

    $all_record_arr[] = $data;  
}

fclose($handle);
?>

Warnings

enter image description here

Prompt

enter image description here

ADyson
  • 57,178
  • 14
  • 51
  • 63
Abhijeet
  • 140
  • 4
  • 14
  • 1
    You can not combine JavaScript and PHP like _that_ - PHP runs on the server, long before any of your JavaScript code executes on the client side. – CBroe Feb 21 '23 at 11:12
  • If you want PHP to be able to read the file, you'd need to upload it to the server first (e.g. via AJAX) and _then_ run the PHP code to process it. – ADyson Feb 21 '23 at 11:14
  • Or if the file is already on the server, then you would simply need a HTML form for the user to enter the desired filename for processing, and then you can submit that form, containing the filename data, to trigger the PHP script to process it. – ADyson Feb 21 '23 at 11:18
  • Okay, thanks for your insights. I will do accordingly @CBroe – Abhijeet Feb 21 '23 at 11:31

0 Answers0