du248227 2012-03-31 03:46
浏览 35
已采纳

上传CSV然后将结果存储到数组中

I've been working on this problem for a few hours and have used many resources from the web and stack overflow, but I can't seem to get past this last thing. I'm in the middle of attempting to get the contents of a csv file and store them in an array and print the results on another page via a session.

index.php (Shows form for uploading file)

<html>
<form action="http://mysite.org/~me/upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file"><br />
<input type="submit" value="Now upload it!">
</form>
</html>

upload.php (if CSV, output filesize, print_r the array that should contain all data)

<?php
session_start();

if (($_FILES["file"]["type"] == "application/vnd.ms-excel"))
{
  if ($_FILES["file"]["error"] > 0)
    {
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    }
else
{
    echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";

    $file = fopen($_FILES["file"]["tmp_name"], 'r');
    while (($line = fgetcsv($file)) !== FALSE) {
    //$line is an array of the csv elements
    print_r($line);
    $_SESSION['line']=$line;

}
fclose($file);

   }
 }
else
 {
 echo "Invalid file";
 }
  echo "<a href='http://mysite.org/~me/yes.php'>Yes</a>";

 ?>

yes.php

<?php
session_start();
$data = $_SESSION['line'];
print_r($data);
?>

The print_r from the upload page should be the same as the print_r from the yes page, but it is not. It is only showing the last array. I don't understand how I would go about this problem.

As a side note: I've only been programming in php for about 2 weeks so please be thoughtful enough to explain your answers. It really helps! Thanks =)

  • 写回答

1条回答 默认 最新

  • douwulu2576 2012-03-31 03:47
    关注

    You need to append instead of overwrite $_SESSION['line'].

    Instead of:

    $_SESSION['line'] = $line; // overwriting $_SESSION['line'] w/ each iteration
    

    You need to:

    $_SESSION['lines'][] = $line; // pushes the line to an array
    

    Then on, yes.php, you can:

    session_start();
    $data = $_SESSION['lines'];
    print_r($data);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路