本文整理汇总了PHP中League\Csv\Reader::createFromPath方法的典型用法代码示例。如果您正苦于以下问题:PHP Reader::createFromPath方法的具体用法?PHP Reader::createFromPath怎么用?PHP Reader::createFromPath使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类League\Csv\Reader
的用法示例。
在下文中一共展示了Reader::createFromPath方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: store
/**
* Store a newly created resource in storage.
*
* @param Request $request
* @return Response
*/
public function store(Request $request)
{
$teachUpload = new Upload();
if (Request::hasFile('upload')) {
$file = Request::file('upload');
$file = $file->move(public_path() . '/uploads/dates', time() . '-' . $file->getClientOriginalName());
$teachUpload->file_path = $file->getRealPath();
$teachUpload->save();
$csvPath = $teachUpload->file_path;
$reader = Reader::createFromPath($csvPath);
$reader->setFlags(SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY);
$reader->setOffset(1);
$pattern = '/([(A-Z)|A-Z]* - .+)/';
$courses = DB::table('courses')->get();
foreach ($reader as $index => $row) {
if ($index != 0) {
$courseNo = $row[1];
$teachDate = $row[5];
$startTime = $row[6];
$endTime = $row[7];
foreach ($courses as $course) {
if ($courseNo == $course->course_no) {
DB::table('dates')->insert(array('course_id' => $course->id, 'teach_date' => $teachDate, 'session_start' => $startTime, 'session_end' => $endTime));
}
}
}
}
}
$teachUpload->save();
return redirect()->route('admin_dates_index')->with('status', 'Teach dates uploaded');
}
示例2: import
public function import(Request $request)
{
if (Request::hasFile('import-file')) {
$file = Request::file('import-file');
$subscribers = \League\Csv\Reader::createFromPath($file);
$subscribers = $subscribers->fetchAssoc();
if (count($subscribers) > 0) {
$mailchimp = new MailChimp();
foreach ($subscribers as $subscriber) {
// create the signup
$signup = new Signup();
$signup->fname = $subscriber['fname'];
$signup->lname = $subscriber['lname'];
$signup->email = $subscriber['email'];
$signup->zip = $subscriber['zip'];
$signup->ip = $_SERVER['REMOTE_ADDR'];
try {
// save the signup
$signup->save();
// add it to mailchimp
$mailchimp->addSubscriber(['email' => $signup->email, 'fname' => $signup->fname, 'lname' => $signup->lname, 'zip' => $signup->zip]);
} catch (\Exception $e) {
}
}
return redirect('admin/subscribers')->withSuccess('Subscribers import completed.');
}
} else {
echo 'no file uploaded';
}
}
示例3: getRecords
/**
* Return an array of records.
*
* @param $limit int
* The number of records to get.
*
* @return object The records.
*/
public function getRecords($limit = null)
{
// Use a static cache to avoid reading the CSV file multiple times.
static $filtered_records;
if (!isset($filtered_records)) {
$inputCsv = Reader::createFromPath($this->input_file);
$inputCsv->setDelimiter($this->field_delimiter);
if (is_null($limit)) {
// Get all records.
$limit = -1;
}
$records = $inputCsv->addFilter(function ($row, $index) {
// Skip header row.
return $index > 0;
})->setLimit($limit)->fetchAssoc();
foreach ($records as $index => &$record) {
if (!is_null($record[$this->record_key]) || strlen($record[$this->record_key])) {
$record = (object) $record;
$record->key = $record->{$this->record_key};
} else {
unset($records[$index]);
}
}
if ($this->fetchermanipulators) {
$filtered_records = $this->applyFetchermanipulators($records);
} else {
$filtered_records = $records;
}
}
return $filtered_records;
}
示例4: parse
/**
* Main parse method
*/
private function parse()
{
$inputCsv = Reader::createFromPath($this->fileName);
$inputCsv->setDelimiter(';');
/**
* get keys from first line
*/
$this->characteristicKeys = $inputCsv->fetchOne();
try {
switch ($this->translatorClass) {
case 'TowerTranslator':
$enemyTrans = new TowerTranslator($this->characteristicKeys);
break;
case 'EnemyTranslator':
$enemyTrans = new EnemyTranslator($this->characteristicKeys);
break;
default:
$enemyTrans = new EnemyTranslator($this->characteristicKeys);
}
$this->characteristicKeys = $enemyTrans->getCharacteristicKeys();
} catch (\Exception $e) {
print_r($e);
}
/**
* get other lines from file to array
*/
$this->characteristic = $inputCsv->fetchAssoc($this->characteristicKeys);
$this->badDataFilter();
}
示例5: handle
/**
* Execute the console command.
*
* @return mixed
*/
public function handle()
{
// read file
$csv = Reader::createFromPath(storage_path($this->argument('file')));
//get the first row, usually the CSV header
$this->headers = collect($csv->fetchOne());
// grab all rows
$rows = $csv->setOffset(1)->fetchAll();
// remove the last row if null
if (!$rows[count($rows) - 1][0]) {
array_pop($rows);
}
// loop them
foreach ($rows as $row) {
// map
$school = School::firstOrNew(['name' => $row[$this->column('SchoolName')]]);
$this->mapData($school, $row);
// save
if ($this->changes($school)) {
$school->save();
}
$this->processed++;
}
$this->comment('Finished Schools Bulk Update');
$this->comment('Processed: ' . $this->processed);
$this->comment('Changed: ' . $this->changes);
}
示例6: import
/**
* @param $fields
* @param $file
* @param $table
* @return mixed
*/
private function import($fields, $file, $table, $insert = true)
{
$this->table = $table;
$this->fields = $fields;
$sql = $this->generateSQL($insert);
$this->sth = $this->dbh->prepare($sql);
$csv = Reader::createFromPath($file);
$header = $csv->fetchOne();
$csv->setOffset(1);
//because we don't want to insert the header
$justDoIT = $csv->each(function ($row) use($header, $sql) {
$this->attachBinds($row, $header);
try {
$exec = $this->sth->execute();
} catch (\ErrorException $e) {
echo $e->getMessage();
}
if (!$exec) {
echo "--DEBUG: ", $sql, $this->lastParams, PHP_EOL;
}
return true;
});
if ($justDoIT) {
return true;
}
//debug -- echo sql and params;
echo "--DEBUG: ", $sql, $this->lastParams, PHP_EOL;
return false;
}
示例7: handle
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$reader = Reader::createFromPath($this->path);
$read = 0;
$saved = 0;
foreach ($reader->fetchAssoc() as $row) {
$read++;
$artist = Artist::firstOrNew(['artist_id' => $row['artist_id']]);
$artist->artist_id = $row['artist_id'];
$artist->slug = $row['slug'];
$artist->name = $row['name'];
$artist->PID = $row['PID'];
$artist->year_birth = $row['year_birth'];
$artist->year_death = $row['year_death'];
$artist->copyright = $row['copyright'];
if ($artist->save()) {
$saved++;
}
}
$report = ['event' => 'artists.imported', 'data' => ['read' => $read, 'saved' => $saved]];
$message = json_encode($report);
$context = new \ZMQContext();
$socket = $context->getSocket(\ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://localhost:5555");
$socket->send($message);
}
示例8: handle
/**
* Execute the console command.
*
* @author Bertrand Kintanar
*/
public function handle()
{
$csv = Reader::createFromPath(storage_path() . '/employee.csv');
$csv->setOffset(2);
$data = $csv->query();
foreach ($data as $lineIndex => $row) {
$data = [];
$data['employee_id'] = $row[0];
$data['joined_date'] = Carbon::parse($row[1])->toDateString();
$data['birth_date'] = Carbon::parse($row[23])->toDateString() ?: null;
$data['first_name'] = utf8_encode($row[4]);
$data['middle_name'] = utf8_encode($row[5]) ?: null;
$data['last_name'] = utf8_encode($row[6]);
$data['suffix_name'] = utf8_encode($row[7]) ?: null;
$data['address_1'] = utf8_encode($row[9]);
$data['address_city_id'] = City::whereName($row[10])->pluck('id') ?: null;
$data['address_province_id'] = 25;
$data['address_country_id'] = 185;
$data['address_postal_code'] = $row[11] ?: null;
$data['social_security'] = $row[15] ?: null;
$data['tax_identification'] = $row[16] ?: null;
$data['philhealth'] = $row[17] ?: null;
$data['hdmf_pagibig'] = $row[18] ?: null;
$data['mid_rtn'] = $row[19] ?: null;
$new_employee = Employee::create($data);
$components = SalaryComponent::all();
foreach ($components as $value) {
$salary_components = ['employee_id' => $new_employee->id, 'component_id' => $value->id, 'value' => 0];
EmployeeSalaryComponent::create($salary_components);
}
}
}
示例9: handle
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$reader = Reader::createFromPath($this->path);
$read = 0;
$saved = 0;
foreach ($reader->fetchAssoc() as $row) {
$read++;
$object_number = $row['object_number'];
unset($row['object_number']);
foreach ($row as $key => $value) {
$document = Document::firstOrNew(['url' => $value]);
$document->object_number = $object_number;
$document->url = $value;
if ($key == "data") {
$document->type = "data";
$document->order = "";
} else {
list($type, $order) = explode("_", $key);
$document->type = $type;
$document->order = isset($order) ? $order : "";
}
if ($document->save()) {
$saved++;
}
}
}
$report = ['event' => 'documents.imported', 'data' => ['read' => $read, 'saved' => $saved]];
$message = json_encode($report);
$context = new \ZMQContext();
$socket = $context->getSocket(\ZMQ::SOCKET_PUSH, 'my pusher');
$socket->connect("tcp://localhost:5555");
$socket->send($message);
}
示例10: getCSV
/**
* Return a CSV reader with the provided document.
*
* @return \League\Csv\Reader
*/
public function getCSV($path)
{
$csv = Reader::createFromPath($path);
$csv->setDelimiter(',');
$csv->setFlags(\SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY);
return $csv;
}
示例11: execute
protected function execute(InputInterface $input, OutputInterface $output)
{
$csvsPath = APP_CWD . '/../csv';
$csvsDatesRegexp = 'd-m-Y';
$menusDatesAlreadyLoaded = array_map(function ($date) use($csvsDatesRegexp) {
return Carbon::parse($date['start_date'])->format($csvsDatesRegexp);
}, Menu::all()->toArray());
$finder = new \Symfony\Component\Finder\Finder();
$finder = $finder->files()->name('*.csv');
foreach ($menusDatesAlreadyLoaded as $date) {
$finder->notPath($date);
}
$files = $finder->in($csvsPath);
foreach ($files as $file) {
list($d, $m, $Y) = explode('-', explode('_', $file->getFilename())[0]);
$menuDate = Carbon::parse("{$Y}-{$m}-{$d}");
$reader = \League\Csv\Reader::createFromPath($file->getPathname());
$results = $reader->setDelimiter(';')->fetchAssoc();
//creazione Menu ed aggiunta del prodotto
$menu = Menu::write($menuDate, $menuDate->copy()->addHours(14));
foreach ($results as $row) {
if (empty($row['Prezzo'])) {
continue;
}
$price = floatval(ltrim(str_replace([','], '.', $row['Prezzo']), '€'));
$category = Product::findCategory($row['Categoria'], false);
//creazione Prodotto
$product = Product::firstOrCreate(['code' => $row['Codice'], 'description' => $row['Descrizione'], 'category' => $category]);
$product->price = $price;
$product->update();
$menu->addProduct($product);
}
}
}
示例12: parseCsvFile
/**
* Parses a csv file into a DataTable.
*
* Pass in a filepath to a csv file and an array of column types:
* ['date', 'number', 'number', 'number'] for example and a DataTable
* will be built.
*
* @access public
* @since 1.0.0
* @param string $filepath Path location to a csv file
* @param array $columnTypes Array of column types to apply to the csv values
* @throws \Khill\Lavacharts\Exceptions\InvalidFunctionParam
* @return \Khill\Lavacharts\DataTable
*/
public function parseCsvFile($filepath, $columnTypes = null)
{
if (Utils::nonEmptyString($filepath) === false) {
throw new InvalidFunctionParam($filepath, __FUNCTION__, 'string');
}
$this->addNewColumns($columnTypes);
$this->setReader(Reader::createFromPath($filepath));
$this->reader->setFlags(\SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY);
$csvColumns = $this->reader->fetchOne();
foreach ($this->newColumns as $index => $column) {
if (in_array($column, $this->columnTypes, true) === false) {
throw new InvalidColumnType($column, Utils::arrayToPipedString($this->columnTypes));
}
$this->addColumnFromStrings($columnTypes[$index], $csvColumns[$index]);
}
$csvRows = $this->reader->setOffset(1)->fetchAll(function ($row) {
return array_map(function ($cell) {
if (is_numeric($cell)) {
return $cell + 0;
} else {
return $cell;
}
}, $row);
});
return $this->addRows($csvRows);
}
示例13: initParser
/**
* Initialises the League CSV Reader if not initialised yet.
* @return Boolean return TRUE if gets initialised or
* FALSE if already initialised
*/
private function initParser()
{
if ($this->csv_reader !== NULL) {
return FALSE;
}
$this->csv_reader = Reader::createFromPath($this->getDatasource());
return TRUE;
}
示例14:
function __construct($pathToCSV, $column = 0)
{
// @todo handle exception (try catch)
$this->mailColumn = $column;
// @see http://csv.thephpleague.com/
// @todo
$this->csv = Reader::createFromPath($pathToCSV);
}
示例15: __construct
public function __construct($file, $helper_column)
{
$this->helper = new \stdClass();
$this->input = $file;
$this->csv = Reader::createFromPath($this->input);
$this->helper->name = $helper_column;
$this->get_offset();
}