如何在php中上传和解析CSV文件
我想用 php 上传 csv 文件。文件上传后,我想显示CSV文件的数据。我想要一个如何完成这项任务的例子。
I want to upload a csv file with php. After the file is uploaded, I want to display the data of the CSV file. I would like an example how to accomplish this task.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
现在可以通过更简单的方式完成此操作。
这将返回一个已解析的 CSV 数据数组。然后您可以使用 foreach 语句循环遍历它。
This can be done in a much simpler manner now.
This will return you a parsed array of your CSV data. Then you can just loop through it using a foreach statement.
未经测试,但应该给你这个想法。视图:
upload.php 控制器:
untested but should give you the idea. the view:
upload.php controller:
虽然您可以轻松找到如何使用 php 处理文件上传的教程,并且有处理 CSV 的函数(手册),但我将发布一些代码,因为就在几天前我在做一个项目,其中包括一些您可以使用的代码使用...
HTML:
PHP:
我知道一定有一种更简单的方法来做到这一点,但我读取了 CSV 文件并将每条记录的单个单元格存储在二维数组中。
所以我希望这会有所帮助,这只是一小段代码,我还没有测试它,因为我使用的它略有不同。评论应该解释一切。
Although you could easily find a tutorial how to handle file uploads with php, and there are functions (manual) to handle CSVs, I will post some code because just a few days ago I worked on a project, including a bit of code you could use...
HTML:
PHP:
I know there must be an easier way to do this, but I read the CSV file and store the single cells of every record in an two dimensional array.
So I hope this will help, it is just a small snippet of code and I have not tested it, because I used it slightly different. The comments should explain everything.
我在 @Thomas Clowes 答案的帮助下创建了下面的代码片段
它将得到如下结果
I have created below snippet with the help of @Thomas Clowes answer
It will get result like below
您需要 PHP 手册中的处理文件上传部分,并且最好查看 fgetcsv() 和explode()。
You want the handling file uploads section of the PHP manual, and you would also do well to look at fgetcsv() and explode().
我觉得
str_getcsv
— 将 CSV 字符串解析为数组是您的最佳选择。您需要将文件上传到服务器。
使用 str_getcsv 解析文件。
遍历数组并根据您的网站需要进行对齐。
I feel
str_getcsv
— Parse a CSV string into an array is the best option for you.You need to upload the file to the server.
Parse the file using str_getcsv.
Run through the array and align as per u need on your website.
你可以尝试用这个:
You can try with this: