Coleen
Coleen

Reputation: 124

How to Link PHP Script with JavaScript and Bootstrap

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?

Upvotes: 1

Views: 87

Answers (2)

bjelleklang
bjelleklang

Reputation: 496

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.

Upvotes: 0

Reagan Gallant
Reagan Gallant

Reputation: 863

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>

Upvotes: 1

Related Questions