本文整理汇总了PHP中League\Csv\Writer::createFromPath方法的典型用法代码示例。如果您正苦于以下问题:PHP Writer::createFromPath方法的具体用法?PHP Writer::createFromPath怎么用?PHP Writer::createFromPath使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类League\Csv\Writer
的用法示例。
在下文中一共展示了Writer::createFromPath方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: 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;
}
示例2: __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);
}
示例3: 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());
}
示例4: createFile
/**
* @throws \RuntimeException
* @param string $file file to write or overwrite
* @param array $data
*/
protected function createFile($file, array $data)
{
$csv = Writer::createFromPath($file, 'w');
$csv->setDelimiter("\t");
$csv->setEnclosure('"');
// we insert the CSV header
$headers = array_keys($data[0]);
$csv->insertOne($headers);
$csv->insertAll($data);
}
示例5: insertInCsv
/**
* Create new csv if needed
* and add request data to csv
*
* @param Reservation $reservation
* @return void
*/
private function insertInCsv(Reservation $reservation)
{
$writer = Writer::createFromPath(Config::get('reservation.csv_path'), 'a');
$writer->setDelimiter(";");
$writer->setEncodingFrom("utf-8");
if (!$this->checkIfCsvExists()) {
// Only add header to first line
$headers = ["Naam", "Voornaam", "E-mail", "Bericht", "Toegevoegd op"];
$writer->insertOne($headers);
}
$writer->insertOne(array($reservation->first_name, $reservation->last_name, $reservation->email, $reservation->message, $reservation->created_at->format('d/m/Y H:i')));
}
示例6: handleData
/**
* Обработка данных и создание нового файла.
*/
public function handleData()
{
try {
$this->reader = Reader::createFromPath($this->pathToReadFile);
$this->writer = Writer::createFromPath($this->pathToWriteFile);
$this->setReadableData();
$this->setFormattedData();
$this->writer->insertAll($this->generateInsertData());
echo 'Data was handled and written to file ' . $this->pathToWriteFile, PHP_EOL;
} catch (\Exception $exception) {
echo $exception->getMessage(), PHP_EOL;
}
}
示例7: publish
/**
* Publish applicable redirects
*
* @return int Number of published redirects
*/
public function publish()
{
if (file_exists($this->redirectsFile)) {
unlink($this->redirectsFile);
}
/** @var Collection $redirects */
$redirects = Redirect::query()->where('is_enabled', '=', 1)->orderBy('sort_order')->get(['id', 'match_type', 'target_type', 'from_url', 'to_url', 'cms_page', 'static_page', 'status_code', 'requirements', 'from_date', 'to_date']);
// TODO: Throw proper exception
try {
$writer = Writer::createFromPath($this->redirectsFile, 'w+');
$writer->insertAll($redirects->toArray());
} catch (\Exception $e) {
// ..
}
return $redirects->count();
}
示例8: loadXlsFile
/**
* Read excel files to all functions in this model
*
* @return mixed
*/
private static function loadXlsFile($typeRead, $type = 'plugin')
{
if ($type == 'plugin') {
$csvReader = Reader::createFromPath(storage_path() . '/recipes.csv');
$csvReader->setDelimiter("\t");
$csvWriter = Writer::createFromPath(storage_path() . '/recipes.csv', 'a');
$csvWriter->setDelimiter("\t");
}
if ($type == 'file') {
self::setFileCsv(storage_path() . '/recipes.csv');
$csvReader = fopen(self::getFileCsv(), 'r');
//self::setTempFileCsv(tempnam(storage_path(), "tmp") );
self::setTempFileCsv(storage_path() . '/recipes.tmp');
$csvWriter = fopen(self::getTempFileCsv(), 'w');
}
$reader = array('reader' => $csvReader, 'writer' => $csvWriter);
return $reader[$typeRead];
}
示例9: makeJournalTransaction
protected function makeJournalTransaction(array $data)
{
if (empty($data)) {
throw new \Exception('Empty data when creating journal Transaction');
}
$corpName = strtolower(str_replace(' ', '_', $data[0]->getAccount()->getCorporation()->getCorporationDetails()->getName()));
$accountName = strtolower(str_replace(' ', '_', $data[0]->getAccount()->getName()));
$fileName = __DIR__ . sprintf('/../../../export/%s_%s_data.%s.csv', $corpName, $accountName, Carbon::now()->toDateTimeString());
if (!file_exists($fileName)) {
$fh = fopen($fileName, 'w');
fclose($fh);
}
$csv = Writer::createFromPath($fileName);
$csv->insertOne(['corp', 'account', 'date', 'time', 'ref_id', 'ref_type_id', 'ref_type', 'owner_name1', 'owner_id1', 'owner_id2', 'arg_name1', 'arg_id1', 'amount', 'balance', 'reason', 'owner1_type_id', 'owner2_type_id']);
$insertData = [];
foreach ($data as $d) {
$arr = ['corp' => $d->getAccount()->getCorporation()->getCorporationDetails()->getName(), 'account' => $d->getAccount()->getName(), 'date' => $d->getDate()->format('m/d/Y'), 'time' => $d->getDate()->format('G:m'), 'ref_id' => $d->getRefId(), 'ref_type_id' => $d->getRefTypeId(), 'ref_type' => $d->getRefType()->getRefTypeName(), 'owner_name1' => $d->getOwnerName1(), 'owner_id1' => $d->getOwnerId1(), 'owner_id2' => $d->getOwnerId2(), 'owner_name2' => $d->getOwnerName2(), 'arg_name1' => $d->getArgName1(), 'arg_id1' => $d->getArgId1(), 'amount' => $d->getAmount(), 'balance' => $d->getBalance(), 'reason' => $d->getReason(), 'owner1_type_id' => $d->getOwner1TypeId(), 'owner2_type_id' => $d->getOwner2TypeId()];
$insertData[] = $arr;
}
$csv->insertAll($insertData);
}
示例10: execute
protected function execute(InputInterface $input, OutputInterface $output)
{
$ti = microtime(true);
$entity_type = $input->getArgument('entity');
$export_fields = explode(",", $input->getOption('fields'));
$max_records = $input->getOption('max');
$skip_records = $input->getOption('skip');
$output_file = $input->getOption('outfile');
$output->writeln(sprintf('<info>Exporting "%s"</info>', $entity_type));
$out_dir = sprintf("%s/output/%s", $this->getApplication()->getAppPath(), $entity_type);
if (!file_exists($out_dir)) {
$output->writeln(sprintf('<error>Directory not found. [%s]</error>', $out_dir));
return;
}
$writer = $output_file ? Writer::createFromPath($output_file, 'w') : $output;
// process fields and build CSV headers
foreach ($export_fields as $i => $field) {
@(list($field, $field_as) = explode(" as ", $field));
$headers[] = $field_as ?: $field;
$export_fields[$i] = $field;
}
$this->write($writer, $headers);
// process each json file file
$idx = 0;
foreach (glob($out_dir . '/*.json') as $file_name) {
if ($idx++ < $skip_records) {
continue;
}
$data = [];
$record = Tools::objectToDotNotationArray(json_decode(file_get_contents($file_name)));
foreach ($export_fields as $field) {
$data[] = isset($record[$field]) ? $record[$field] : null;
}
$this->write($writer, $data);
if ($idx == $max_records + $skip_records) {
break;
}
}
$output->writeln(sprintf("<info>Finished exporting %d \"%s\" records in %01.1f seconds</info>", $idx, $entity_type, microtime(true) - $ti));
}
示例11: execute
/**
* Merges benchmark
*
* @param InputInterface $input
* @param OutputInterface $output
* @return int
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$files = $this->resolveFiles($input->getArgument('path'));
if (empty($files)) {
throw new \InvalidArgumentException('No readable files has been provided');
}
foreach ($files as $file) {
$reader = Reader::createFromPath($file);
$basename = basename($file);
$output = Writer::createFromPath(rtrim($input->getOption('output-path'), '/') . $basename);
$matrix = [];
$samples = [];
foreach ($reader->fetchAssoc() as $row) {
$samples[$row['sample']] = true;
$matrix[$row['operation']][$row['sample']] = $row['total'];
}
$output->insertOne(array_merge(['Operation'], array_keys($samples)));
foreach ($matrix as $code => $row) {
$output->insertOne(array_merge([$code], array_values($row)));
}
}
}
示例12: HtmlDomParser
use League\Csv\Writer;
# Store url
$url = "http://centrodosuplemento.com.br/suplementos";
$html = new HtmlDomParser();
$html->loadUrl($url);
$page_numbers = [];
foreach ($html->find('.toolbar-bottom .pager .pages ol li') as $page) {
$page_numbers[] = $page->plaintext;
}
$max_page = max($page_numbers);
# Initialize Arrays
$name = [];
$price = [];
for ($i = 1; $i <= $max_page; $i++) {
# Open search results page
$url = "http://centrodosuplemento.com.br/suplementos?mode=list?p={$i}";
$product_html = new HtmlDomParser();
$product_html->loadUrl($url);
# Store data in Arrays
foreach ($product_html->find('.product-name a') as $line) {
$name[] = $line->plaintext;
}
foreach ($product_html->find('.price-box .regular-price .price') as $line) {
$price[] = $line->plaintext;
}
}
$writer = Writer::createFromPath('cds_list.csv', 'w');
$writer->insertOne(["Listing Name", "Price"]);
for ($p = 0; $p < count($name); $p++) {
$writer->insertOne([$name[$p], $price[$p]]);
}
示例13: getWriter
protected function getWriter($path = null)
{
if ($path === null) {
$path = $this->getFile();
}
return Writer::createFromPath($path, 'a+');
}
示例14: store
/**
* Store Requested data.
*
* @param $request
*
* @return static
*/
public function store($request)
{
$file = $this->checkCsvFile();
$writer = Writer::createFromPath(new SplFileObject($file), 'a');
return $writer->insertOne($request->only($this->allowedFields));
}
示例15: writerTest
/**
* {@inheritdoc}
*/
public function writerTest()
{
$csv = Writer::createFromPath($this->path, 'w');
$csv->insertAll($this->generateRawData());
}