1

I am trying to take a CSV file from the client side and read it in order to create arrays that can then be used in my original html file, that contains javascript, to create a dynamic table. My PHP code for parsing into arrays is:

<php?
$csvData = file_get_contents($fileName);
$lines = explode(PHP_EOL, $csvData);
$array = array();
foreach ($lines as $line) {
    $array[] = str_getcsv($line);
}
print_r($array);
?>

And my HTML (a simple file upload) is:

<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload CSV" name="submit">

but I am unsure as to how I should connect these pieces? Can the PHP script be in the same document as the HTML(which contains the JS to construct the table), or should it be called through a form?

2 Answers 2

1

Save your php script in a file eg. upload.php. Then use the following code in your html:

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileToUpload">
    <input type="submit" value="Upload CSV" name="submit">
</form>
Sign up to request clarification or add additional context in comments.

3 Comments

And to access the arrays built, can i simply use a json function? And how would the user return to the original page without losing php data from the file?
You can ajax to post the file . The you don't need to worry about redirecting. The content can be access by using the name file element eg. "fileToUpload". You can test it print_r($_FILES['fileToUpload']);
Thanks so much for all the help!
0

The easiest way to output the csv based on Reagan Gallant's suggestion above, is to print the data directly from upload.php. You can also add a header saying that you're serving csv, and let the browser decide what to do (save as file, display in browser):

header('Content-Type: text/csv'); print $csv;

Or you can use a javascript library such as JQuery to upload the file and return the result using ajax. This requires a little bit extra coding, but depending on your goal it might be worthwhile.

2 Comments

The header/print statement would be inserted into upload.php, and is used at the end. Keep in mind that the call to header must be the first output from the script, otherwise the call will fail. See php.net/manual/en/function.header.php for more information.
Thanks so much, I'll check that out!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.