轻松生成CSV文件

1.8 2015-08-17 13:51 UTC

This package is not auto-updated.

Last update: 2024-09-20 21:52:41 UTC


README

Build Status

简单CSV文件操作(读取、写入和下载)

这是一个简单的实用程序包,帮助您处理CSV文件。

##使用Composer安装

将此行添加到您的composer.json文件中的`require`字段

"mnshankar/CSV": "1.8"

##通用PHP项目或Laravel 5+项目

由于此包没有特定于框架的依赖(或任何依赖),您可以直接在代码中实例化CSV对象,如下所示

$csvObj = new mnshankar\CSV\CSV();

然后,使用常规PHP对象调用,如下所示

$arr = array(
    array('col1'=>'a','col2'=>'b'),
    array('col1'=>'1','col2'=>'2'),
    array('col1'=>'3','col2'=>'4'),
);
return $csvObj->fromArray($arr)->render('myfile.csv');                  //download as csv;
return $csvObj->fromArray($arr)->withSeparator()->render('myfile.csv'); //add delimiter for better excel compatibility & download
return $csvObj->with($arr)->put('/downloads/myusers.csv');	            //store as csv in this path
return $csvObj->fromFile('/downloads/my.csv')->toArray();               //return csv file as an array
return $csvObj->fromFile('/downloads/my.csv')->render('abc.csv');       //render saved csv file as a downloadable document
return $csvObj->with('/downloads/my.csv')->render('abc.csv');           //use 'with'.. same as previous

##Laravel 4 CSV(可选)支持Laravel,并附带Service Provider和Facades以方便集成。打开app/config/app.php,在`providers`数组中添加以下行

'providers' => array(
    'mnshankar\CSV\CSVServiceProvider',
)

并在`alias`数组中添加以下内容

'alias' => array(
    'CSV'             =>'mnshankar\CSV\CSVFacade',
)

现在,在您的应用程序中,您可以如此处理CSV文件

$arr = User::all()->toArray();	//use eloquent to get array of all users in 'users' table

return CSV::with($arr)->put(storage_path().'/downloads/myusers.csv');	//store as csv in this path
return CSV::fromArray($arr)->render();	//download as csv
return CSV::fromFile(storage_path().'/downloads/my.csv')->toArray();    //return csv file as an array
return CSV::fromFile(storage_path().'/downloads/my.csv')->render('abc.csv'); //render saved csv file as a downloadable document
return CSV::with(storage_path().'/downloads/my.csv')->render('abc.csv'); //use 'with'.. same as previous

请注意,`with`语句可以接受数组或文件路径,并相应地处理。

许可证

这是一个开源软件,受MIT许可证许可。