I am attempting to upload a CSV file ONLY, using a HTML form, then using PHP and Javascript to save it in an array.
I have some code, that is working perfectly as separate files. Although, when I try to merge them into the one file, it refuses to work and the Javascript array ends up just alerting as null.
I am trying to only call the PHP if the form has been posted, and then calling the Javascript only when the submit button has been pressed.
The separated version - WORKING
The HTML
<form action="yourscript.php" method="post" enctype="multipart/form-data">
<input type="file" name="upload_file" />
<input type="submit" />
</form>
The Javascript and PHP
<?php
$csv_array = Array();
$file = fopen($_FILES['upload_file']['tmp_name'], 'r');
if($file){
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
array_push($csv_array,$line);
}
fclose($file);
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>var your_array = <?php echo json_encode($csv_array); ?></script>
</head>
<body>
</body>
</html>
The merged version - NOT WORKING
<?php
if(isset($_POST['savecsv']))
{
$csv_array = Array();
$file = fopen($_FILES['upload_file']['tmp_name'], 'r');
if($file)
{
while (($line = fgetcsv($file)) !== FALSE)
{
//$line is an array of the csv elements
array_push($csv_array,$line);
}
fclose($file);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
function saveArray()
{
var your_array = <?php echo json_encode($csv_array); ?>
alert(your_array);
}
</script>
</head>
<body>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input type="file" name="upload_file" />
<input type="submit" name="savecsv" onClick="saveArray();"/>
</form>
</body>
</html>