1. Composer的安装
Linux/Mac:
curl -sS https://getcomposer.org/installer | php
Windows:
下载后安装,将会安装最新版的Composer
2. Composer的使用
这里使用League\Csv 进行Csv文件的读取和写入
首先需要在项目根目录使用Composer命令下载leaque/csv:
composer require league/csv
执行后会在项目顶层目录下生成composer.lock文件和composer.json文件
示例代码:
<?php
require 'vendor/autoload.php';
use League\Csv\Reader;
use League\Csv\Writer;
// Get the instance of Guzzle HTTP client.
$client = new \GuzzleHttp\Client();
/**
* Read CSV file sample.
*/
//load the CSV document from a file path
$csv = Reader::createFromPath('D:\wamp\www\yixun\test.csv', 'r');
$csv->setHeaderOffset(0);
$header = $csv->getHeader();
$records = $csv->getRecords();
echo $csv->getContent();
/**
* Write CSV file sample.
*/
$header = ['Site', 'Description', 'URL'];
$records = [
['League/Csv', 'The PHP League composer official site', 'https://csv.thephpleague.com/'],
['Symfony', 'Symfony official site', 'https://symfony.com'],
['Laravel', 'Laravel official site', 'https://laravel.com'],
];
//load the CSV document from a string
$csv1 = Writer::createFromString('');
//insert the header
$csv1->insertOne($header);
//insert all the records
$csv1->insertAll($records);
echo $csv1->getContent(); //returns the CSV document as a string
$csv2 = Writer::createFromPath("D:\wamp\www\yixun\out.csv",'w');
$csv2->setOutputBOM(Writer::BOM_UTF8);
$csv2->insertOne($header);
$csv2->insertAll($records);
?>
执行结果