沃梦达 / 编程问答 / php问题 / 正文

在 yii 中从 csv 文件导入和保存数据

Importing and saving data from csv file in yii(在 yii 中从 csv 文件导入和保存数据)

本文介绍了在 yii 中从 csv 文件导入和保存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 csv 文件的样子:

This is what my csv file looks like:

我有三个字段(import siteimport goodsimport status)来导入各自的数据.因此,如果用户点击import site,则只会保存站点名称,其余的不会保存,对于import goodsimport status 也是如此.

I have three fields (import site, import goods, import status) to import respective data. So if a user clicks on import site only sites name will get saved and the rest won't, similarly for import goods and import status.

site's 数据和 status' 数据保存在一个表中,而 goods 数据保存在其他表中.地点.如何将它们保存到多个表中?

The site's data and status's data are saved in a single table but the goods data is being saved in other table with respect to it's site. How do i save them into multiple tables?

推荐答案

我将分享一个简单的片段来解析 csv 文件,也许这可以帮助

I will share simple snippet to parse csv files, maybe this can help

$i=0; $keys=array();$output=array();
        $handle=fopen($filename, "r");
        if ($handle){
             while(($line = fgetcsv($handle)) !== false) {
                $i++;
                if ($i==1) {
                   $keys=$line;
                }
                elseif ($i>1){ 
                    $attr=array();
                    foreach($line as $k=>$v){
                        $attr[$keys[$k]]=$v;
                    }
                    $output[]=$attr;
                }    
             }
            fclose($handle);
        }

这将完成这项工作,我总是在使用 csv 时使用它.为了使这个工作第一行必须包含键,例如:

This will do the job, i'm using it always when come to csv. To make this work 1st line must contain keys, for example:

import_site, import_goods, import_status

在您的 $output 数组中,您将拥有带有键 $output["import_site"] 等的数据.

In your $output array you'll have data with keys $output["import_site"] and so on.

希望这会有所帮助.

这篇关于在 yii 中从 csv 文件导入和保存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:在 yii 中从 csv 文件导入和保存数据

基础教程推荐