本文整理汇总了PHP中League\Csv\Writer类的典型用法代码示例。如果您正苦于以下问题:PHP Writer类的具体用法?PHP Writer怎么用?PHP Writer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Writer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: fire
/**
* Execute the console command.
*
* @return mixed
*/
public function fire()
{
$experiments = Experiment::active()->get();
$goals = array_unique(Goal::active()->orderBy('name')->lists('name')->toArray());
$columns = array_merge(['Experiment', 'Visitors', 'Engagement'], array_map('ucfirst', $goals));
$writer = new Writer(new SplTempFileObject());
$writer->insertOne($columns);
foreach ($experiments as $experiment) {
$engagement = $experiment->visitors ? $experiment->engagement / $experiment->visitors * 100 : 0;
$row = [$experiment->name, $experiment->visitors, number_format($engagement, 2) . " % (" . $experiment->engagement . ")"];
$results = $experiment->goals()->lists('count', 'name');
foreach ($goals as $column) {
$count = array_get($results, $column, 0);
$percentage = $experiment->visitors ? $count / $experiment->visitors * 100 : 0;
$row[] = number_format($percentage, 2) . " % ({$count})";
}
$writer->insertOne($row);
}
$output = (string) $writer;
if ($file = $this->argument('file')) {
$this->info("Creating {$file}");
File::put($file, $output);
} else {
$this->line($output);
}
}
示例2: handle
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
* @throws RedirectException
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$source = $request->get('source', 'api_data');
$filename = $request->get('filename', 'export_' . date('Y-m-d_Hi'));
if ($request->get('download') && array_key_exists($source, $response->original->getData())) {
switch ($request->get('download')) {
case 'json':
return response()->json($response->original->getData()[$source], 200, ['Content-Disposition' => 'attachment; filename="' . $filename . '.json"']);
case 'csv':
$writer = Writer::createFromFileObject(new \SplTempFileObject());
$writer->setDelimiter(',');
$writer->setNewline("\r\n");
$writer->setEncodingFrom("utf-8");
$headers = ['Content-Type' => 'text/csv', 'Content-Disposition' => 'attachment; filename="' . $filename . '.csv"'];
$csv_headers_set = false;
foreach ($response->original->getData()[$source] as $data) {
if (!$csv_headers_set) {
$writer->insertOne(array_keys($this->getArrayRepresentation($data)));
$csv_headers_set = true;
}
$writer->insertOne($this->processData($this->getArrayRepresentation($data)));
}
return response()->make($writer, 200, $headers);
default:
throw RedirectException::make('/')->setError('Unrecognised type to download');
}
}
return $response;
}
示例3: execute
protected function execute(InputInterface $input, OutputInterface $output)
{
$this->writeSection($output, 'Po to Csv converter');
$this->cwd = getcwd() . DIRECTORY_SEPARATOR;
$output->writeln('<info>Using CWD</info> ' . $this->cwd);
$poFiles = $this->getInputPoFiles($input, $output);
$outputFolder = $this->getOutputFolder($input, $output);
$useDefaults = $input->getOption('use-defaults');
if ($useDefaults) {
$output->writeln('<info>Po files</info>:');
$this->writeList($output, $poFiles);
$output->writeln(['', '<info>Output folder</info>: ' . $outputFolder]);
}
$poHandles = [];
foreach ($poFiles as $poFile) {
$key = basename($poFile, '.po');
$output->writeln('<info>loading ' . $key . '</info>...');
$poHandles[$key] = Translations::fromPoFile($poFile);
}
$output->writeln('<info>merging po files</info>...');
$csvArray = [];
foreach ($poHandles as $language => $poHandle) {
foreach ($poHandle as $translation) {
$original = trim($translation->original);
$translation = trim($translation->translation);
if (!isset($csvArray[$original])) {
$csvArray[$original] = [$language => $translation];
} elseif (!isset($csvArray[$original][$language])) {
$csvArray[$original][$language] = $translation;
} elseif ($csvArray[$original][$language] != $translation) {
$csvArray[$original][$language] = $this->handleConflict($input, $output, $original, $csvArray[$original][$language], $translation);
}
}
}
$output->writeln('<info>writing csv</info>...');
$writer = Writer::createFromFileObject(new SplTempFileObject());
$writer->setDelimiter(';');
$header = ['original'];
$header = array_merge($header, array_keys($poHandles));
$writer->insertOne($header);
foreach ($csvArray as $original => $item) {
$row = [];
foreach ($header as $column) {
if ($column === 'original') {
$row[] = $original;
} else {
$row[] = isset($item[$column]) ? $item[$column] : null;
}
}
$writer->insertOne($row);
}
$outputFile = $outputFolder . DIRECTORY_SEPARATOR . 'translations.csv';
file_put_contents($outputFile, $writer->__toString());
$output->writeln('<info>done. output file is</info> ' . $outputFile);
}
示例4: run
/**
* @return bool
*/
public function run() : bool
{
// create temporary file:
$this->tempFile();
// necessary for CSV writer:
$fullPath = storage_path('export') . DIRECTORY_SEPARATOR . $this->fileName;
$writer = Writer::createFromPath(new SplFileObject($fullPath, 'a+'), 'w');
$rows = [];
// Count the maximum number of sources and destinations each entry has. May need to expand the number of export fields:
$maxSourceAccounts = 1;
$maxDestAccounts = 1;
/** @var Entry $entry */
foreach ($this->getEntries() as $entry) {
$sources = $entry->sourceAccounts->count();
$destinations = $entry->destinationAccounts->count();
$maxSourceAccounts = max($maxSourceAccounts, $sources);
$maxDestAccounts = max($maxDestAccounts, $destinations);
}
$rows[] = array_keys($this->getFieldsAndTypes($maxSourceAccounts, $maxDestAccounts));
/** @var Entry $entry */
foreach ($this->getEntries() as $entry) {
// order is defined in Entry::getFieldsAndTypes.
$current = [$entry->description, $entry->amount, $entry->date];
$sourceData = $this->getAccountData($maxSourceAccounts, $entry->sourceAccounts);
$current = array_merge($current, $sourceData);
$destData = $this->getAccountData($maxDestAccounts, $entry->destinationAccounts);
$current = array_merge($current, $destData);
$rest = [$entry->budget->budgetId, $entry->budget->name, $entry->category->categoryId, $entry->category->name, $entry->bill->billId, $entry->bill->name];
$current = array_merge($current, $rest);
$rows[] = $current;
}
$writer->insertAll($rows);
return true;
}
示例5: handle
/**
* Execute the job.
*
* @return void
*/
public function handle(MergeManager $mergeManager, FileManager $fileManager)
{
$columns = ['PID', 'entity type', 'title', 'document type', 'URL', 'enabled', 'notes', 'format', 'reference', 'order'];
$items = $mergeManager->fetchAll();
$writer = Writer::createFromFileObject(new SplTempFileObject());
$writer->insertOne($columns);
$count = 0;
foreach ($items as $item) {
$row = [$item->object_number, $item->entity_type, $item->object->title, $item->url, $item->enabled, $item->format, $item->representation_order, $item->reference];
$writer->insertOne($row);
$count++;
}
$output = (string) $writer;
$timestamp = Carbon::now();
$fileName = sprintf("import_%s.csv", $timestamp->format('dmY_His'));
$fileManager->saveFile($fileName, $output);
$merger = new Merger();
$merger->filename = $fileName;
$merger->documents = $count;
$merger->save();
$context = new \ZMQContext();
$socket = $context->getSocket(\ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://localhost:5555");
$socket->send('test');
}
示例6: table
/**
* Overload render for array data output
*
* @param \FrenchFrogs\Table\Table\Table $table
* @return array
*/
public function table(Table\Table $table)
{
// INitilisation du CSV
$csv = Writer::createFromFileObject(new \SplTempFileObject());
// gestion des colonne
$header = $columns = [];
foreach ($table->getColumns() as $index => $column) {
// Seule les colonnes Exportable peuvent être exporté
if ($column instanceof Exportable) {
$columns[$index] = $column;
$header[$index] = $column->getLabel();
}
}
// insertion du header
$csv->insertOne(array_values($header));
//@todo mettre en place un streaming pour économiser la memoire
// insertion des lignes
foreach ($table->getRows() as $row) {
$line = [];
foreach (array_keys($header) as $index) {
$line[] = $columns[$index]->getValue($row);
}
$csv->insertOne($line);
}
$csv->output($table->getFilename());
exit;
}
示例7: exportSelected
public function exportSelected()
{
$selected_students = Input::get('studentId');
if (is_array($selected_students)) {
//Setup CSV
$csv = \League\Csv\Writer::createFromFileObject(new \SplTempFileObject());
$column_flag = false;
$student = [];
foreach ($selected_students as $student_id) {
$student_data = Students::with('course')->find($student_id);
//Personal data
$student['firstname'] = $student_data['firstname'];
$student['surname'] = $student_data['surname'];
$student['email'] = $student_data['email'];
//Course data
$student['university'] = $student_data->course['university'];
$student['course_name'] = $student_data->course['course_name'];
//Check whether column headers have been set (not ideal for large datasets)
if ($column_flag === false) {
$csv->insertOne(\Schema::getColumnListing('student'));
$column_flag = true;
}
//Add student record to file
$csv->insertOne($student);
}
} else {
return "NO STUDENTS SELECTED";
}
//is_array($selected_students)
$csv->output("selected_student_records.csv");
}
示例8: run
public function run()
{
$commandResult = $this->runCommandPrompt();
$salaryCalendar = SalaryCalendar::get($commandResult['startDate'], $commandResult['endDate'], $commandResult['year']);
$csvWriter = Writer::createFromFileObject(new \SplTempFileObject());
$writer = new CsvFileWriter($csvWriter, $salaryCalendar->calculatePayDays());
$writer->write($commandResult['path'] . DIRECTORY_SEPARATOR . $commandResult['name']);
}
示例9: testInsertNormalFile
public function testInsertNormalFile()
{
$csv = Writer::createFromPath(__DIR__ . '/foo.csv', 'a+');
$csv->insertOne(['jane', 'doe', 'jane.doe@example.com']);
$iterator = new LimitIterator($csv->getIterator(), 1, 1);
$iterator->rewind();
$this->assertSame(['jane', 'doe', 'jane.doe@example.com'], $iterator->getInnerIterator()->current());
}
示例10: __construct
/**
* Create CSV file
*
*/
public function __construct()
{
if (empty($filepath)) {
$this->filepath = realpath(dirname(__FILE__) . '/../') . '/' . $this->filename;
}
$this->csv = \League\Csv\Writer::createFromPath(new \SplFileObject($this->filepath, 'w+'), 'w');
$this->csv->insertOne($this->columns);
}
示例11: exportToFile
/**
* Exports $result to $file.
*/
public function exportToFile(array $result, $file)
{
$writer = Writer::createFromFileObject(new SplTempFileObject());
foreach ($result['result'] as $row) {
unset($row['_id']);
$writer->insertOne($row);
}
file_put_contents($file, $writer->__toString());
}
示例12: export
public function export()
{
$data = $this->formatData();
$keys = array_keys($data[0]);
$csv = Writer::createFromFileObject(new SplTempFileObject());
$csv->insertOne($keys);
$csv->insertAll($data);
return (string) $csv;
}
示例13: export
public function export()
{
$data = $this->formatData();
$keys = array_keys($data[0]);
$csv = Writer::createFromFileObject(new SplTempFileObject());
$csv->insertOne($keys);
$csv->insertAll($data);
$csv->output($this->getFileName());
}
示例14: createCsv
private function createCsv($inquiryList)
{
$writer = Writer::createFromString("");
$writer->setNewline("\r\n");
foreach ($inquiryList as $inquiry) {
/** @var Inquiry $inquiry */
$writer->insertOne([$inquiry->getId(), $inquiry->getName(), $inquiry->getEmail()]);
}
return (string) $writer;
}
示例15: create
/**
* Show the form for creating a new resource.
*
* @return Response
*/
public function create()
{
$people = bbStock::all();
$csv = \League\Csv\Writer::createFromFileObject(new \SplTempFileObject());
$csv->insertOne(\Schema::getColumnListing('bbstock'));
foreach ($people as $person) {
$csv->insertOne($person->toArray());
}
$csv->output('bbstock.csv');
}