/** * 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'); }
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'; } }
/** * 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; }
/** * 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(); }
/** * 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); }
/** * @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; }
/** * 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); }
/** * 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); } } }
/** * 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); }
/** * 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; }
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); } } }
/** * 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); }
/** * 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; }
function __construct($pathToCSV, $column = 0) { // @todo handle exception (try catch) $this->mailColumn = $column; // @see http://csv.thephpleague.com/ // @todo $this->csv = Reader::createFromPath($pathToCSV); }
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(); }
/** * Get headers from path * * @param string $path Path to file * @return array */ public function getHeadersFromPath($path) { $result = []; $this->validatePath($path); $reader = Reader::createFromPath($path, $this->open_mode); $result = $reader->fetchOne(); return $result; }
/** * Store a newly created resource in storage. * * @param Request $request * @return Response */ public function store(Request $request) { $upload = new Course(); if (Request::hasFile('upload')) { $file = Request::file('upload'); //$file = $file->move(public_path() . '/uploads/courses', time() .'-' . $file->getClientOriginalName()); $upload->file_path = $file->getRealPath(); //$upload->save(); $csvPath = $upload->file_path; $reader = Reader::createFromPath($csvPath); $reader->setFlags(SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY); $reader->setOffset(1); $pattern = '/([(A-Z)|A-Z]* - .+)/'; $paperPattern = '/\\b(ACCA|CIMA)\\b/'; $centres = DB::table('centres')->get(); $papers = DB::table('papers')->get(); foreach ($reader as $index => $row) { if ($index != 0) { $centreCode = $row[0]; $courseNo = $row[1]; $courseName = $row[2]; $startDate = $row[5]; $status = $row[8]; $price = $row[9]; /*foreach ($centres as $centre) { if($centreCode == $centre->centre_code) { $centreId = $centre->id; preg_match($pattern, $courseName, $matches); DB::table('courses')->insert( array( 'course_no' => $courseNo, 'name' => $matches[0], 'start_date' => $startDate, 'price' => $price, 'status' => $status, 'centre_id' => $centreId, ) ); } } */ foreach ($papers as $paper) { preg_match($paperPattern, $courseName, $paperMatch); dd($paperMatch); } } } } $upload->save(); return redirect('courses')->with('status', 'Courses Uploaded'); }
/** * @param string $filePath Path to the csv file to read from * @param string $delimiter The delimiter for the csv file * @param string $enclosure The enclosure for the csv file */ public function __construct($filePath, $delimiter = ',', $enclosure = '"') { if (!is_file($filePath)) { throw new LogicException(sprintf('The file %s does not exist. \\Plum\\PlumCsv\\CsvReader needs an existing csv to work with', $filePath)); } $this->csv = Reader::createFromPath($filePath); $this->csv->setFlags(\SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY); $this->csv->setDelimiter($delimiter); $this->csv->setEnclosure($enclosure); }
/** * @return string */ public function randomAttribution() { if (!ini_get('auto_detect_line_endings')) { ini_set('auto_detect_line_endings', '1'); } $famousPeople = Reader::createFromPath(resources_path('quotes/famous-people.txt')); $res = $famousPeople->fetchAssoc(['code', 'name']); $resToArray = iterator_to_array($res, false); return $resToArray[array_rand($resToArray, 1)]['name']; }
private function getMappingsArray($mappingCSVpath, $numOfFields = 3) { $filename = $mappingCSVpath; $reader = Reader::createFromPath($filename); $collectionMappingArray = array(); foreach ($reader as $index => $row) { $collectionMappingArray[$row[0]] = $row; } return $collectionMappingArray; }
/** * Get total row count */ private function rowCount($file, $mac) { if ($mac && !ini_get("auto_detect_line_endings")) { ini_set("auto_detect_line_endings", '1'); } $csv = Reader::createFromPath($file); $count = $csv->each(function () { return true; }); return $count; }
/** * Get paginated client list. * * @param $perPage * @param $request * * @return mixed */ public function paginated($perPage, $request) { $this->checkCsvFile(); $page = $request->query('page', 1); $offset = ($page - 1) * $perPage; $clients = Reader::createFromPath(storage_path('app/client.csv')); $total = $clients->each(function () { return true; }); return (new LengthAwarePaginator($clients->setOffset($offset)->setLimit($perPage)->fetchAssoc($this->allowedFields), $total, $perPage))->setPath('client'); }
/** * Get the columns for a given row */ public function getRow($row) { $this->setFile(); $this->setMacFormatting(); $csv = Reader::createFromPath($this->file['file']); $res = $csv->fetchOne($row); if (!$res) { throw new \Exception(__('Row not found', 'wpsimplelocator')); } return $res; }
/** * Show all reservation entries * from data.csv * * @return \Illuminate\Http\Response */ public function entries() { $filePath = Config::get('reservation.csv_path'); if (File::exists($filePath)) { $csv = Reader::createFromPath($filePath); $csv->setDelimiter(';'); $headers = $csv->fetchOne(0); $entries = $csv->setOffset(1)->fetchAll(); } return View::make('pages.entries', compact('headers', 'entries')); }
/** * Handle the event. * * @param FileWasUploaded $event * @return void */ public function handle($event) { $csv = Reader::createFromPath(storage_path('app/processing/' . $event->file)); foreach ($csv->fetchAssoc() as $document) { if ($document['reference']) { $this->documents->create($document); $job = (new Generator($document))->onQueue('generator'); $this->dispatch($job); } } Log::info('iterate over data, passing each document out to a queue'); }
/** * Run the database seeds. * * @return void */ public function run() { // Read the database of allied awards $csv = Reader::createFromPath(storage_path('app/csv/issued_allied_awards.csv')); // This will read the CSV as set of data into the listed array keys $data = $csv->fetchAssoc(['playerName', 'playerLabel', 'awardName', 'campaign_id', 'awardedAt', 'submitterName', 'cincName', 'forumSource'], function ($row) { // manipulate the incoming data as it is read. This is turn it into // a set of data which can be immediately added to our awards table $drow = []; $drow['playerName'] = trim(strtolower($row[1])); $drow['playerLabel'] = trim($row[1]); // case as it appears in csv $drow['awardName'] = snake_case(strtolower(trim($row[2]))); $drow['campaign_id'] = trim($row[3]) == '' ? null : trim($row[3]); $drow['awardedAt'] = trim($row[6]); $drow['submitterName'] = trim(strtolower($row[7])); $drow['cincName'] = trim(strtolower($row[8])); $drow['forumSource'] = trim(strtolower($row[9])); return $drow; }); Player::unguard(); foreach ($data as $item) { $award = Award::where('key', $item['awardName'])->first(); if ($award == null) { Log::info(sprintf('Could not find an award with key %s', $item['awardName'])); continue; } $submitter = Player::where('playerName', $item['submitterName'])->first(); if ($submitter == null) { $submitter = Player::create(['playerName' => $item['submitterName'], 'isActive' => true]); } $cinc = Player::where('playerName', $item['cincName'])->first(); if ($cinc == null) { $cinc = Player::create(['playerName' => $item['cincName'], 'isActive' => true]); } // check the rype of award we are presenting. If it's a squad award, find the squad and apply it // also, if there is a space in the name, its not a player name if ($award->awardedTo == 'squad' || preg_match('/\\s/', $item['playerName']) > 0) { $squad = Squad::where('key', snake_case($item['playerName']))->first(); if ($squad == null) { $squad = Squad::create(['key' => snake_case($item['playerName']), 'label' => $item['playerLabel'], 'isActive' => true]); } $squad->awards()->save($award, ['awardedBy_id' => $submitter->id, 'cinc_id' => $cinc->id, 'campaign_id' => $item['campaign_id'], 'awardedAt' => Carbon\Carbon::createFromFormat('d/m/Y', $item['awardedAt']), 'forumLink' => $item['forumSource']]); } else { $player = Player::where('playerName', $item['playerName'])->first(); if ($player == null) { $player = Player::create(['playerName' => $item['playerName'], 'isActive' => true]); } $player->awards()->save($award, ['awardedBy_id' => $submitter->id, 'cinc_id' => $cinc->id, 'campaign_id' => $item['campaign_id'], 'awardedAt' => Carbon\Carbon::createFromFormat('d/m/Y', $item['awardedAt']), 'forumLink' => $item['forumSource']]); } } Player::reguard(); }
public function run() { // Uncomment the below to wipe the table clean before populating DB::table('entity_iso_names')->delete(); //reset autoincrement $statement = "ALTER TABLE entity_iso_names AUTO_INCREMENT = 1;"; DB::unprepared($statement); //load file with data $filename = "/_projects/oxford/_pieces/data/iso4.csv"; $csv = \League\Csv\Reader::createFromPath($filename); DB::table('entity_iso_names')->insert($csv->fetchAssoc()); }
public function run() { DB::statement("TRUNCATE TABLE cities CASCADE"); $reader = Reader::createFromPath(base_path() . '/database/municipios.csv'); foreach ($reader as $index => $row) { if (isset($row[1]) and isset($row[2]) and isset($row[3])) { $name = ucfirst(mb_strtolower($row[3], 'UTF-8')); $city = new City(['name' => $name, 'state_id' => $row[1]]); $city->id = $row[2]; $city->save(); } } }
/** * @param callable|null $callback */ public function run(callable $callback = null) { $reader = Reader::createFromPath($this->fixture); $columns = $reader->fetchOne(); $reader->setOffset(1); $reader->addFilter(function ($data) { return array_filter($data); }); $items = $reader->fetchAssoc($columns); foreach ($items as $item) { $this->useCallable($callback, $item); } }
protected function execute(InputInterface $input, OutputInterface $output) { $this->writeSection($output, 'Csv to Po converter'); $this->cwd = getcwd() . DIRECTORY_SEPARATOR; $output->writeln('<info>Using CWD</info> ' . $this->cwd); $csvFile = $this->getInputCsvFile($input, $output); $poFiles = $this->getInputPoFiles($input, $output); $outputFolder = $this->getOutputFolder($input, $output); $useDefaults = $input->getOption('use-defaults'); if ($useDefaults) { $output->writeln('<info>Csv file</info>:' . "\n" . $csvFile . "\n"); $output->writeln('<info>Po files</info>:'); $this->writeList($output, $poFiles); $output->writeln("\n" . '<info>Output folder</info>: ' . "\n" . $outputFolder . "\n"); } $writeHandles = []; foreach ($poFiles as $poFile) { $key = basename($poFile, '.po'); $output->writeln('<info>loading ' . $key . '</info>...'); $writeHandles[$key] = Translations::fromPoFile($poFile); } $header = null; $output->writeln('<info>reading from csv</info>...'); $reader = Reader::createFromPath($csvFile); foreach ($reader as $i => $row) { if ($header == null) { $header = $row; continue; } $original = null; foreach ($row as $j => $string) { if ($original == null) { $original = $string; continue; } if (empty($string)) { continue; } $writeHandle = $writeHandles[$header[$j]]; $translation = $writeHandle->find(null, $original); if ($translation != false && $translation->translation != $string) { if (!empty($translation->translation)) { $this->handleConflict($input, $output, $original, $translation->translation, $string); } else { $translation->setTranslation($string); } } else { $translation = new Translation(null, $original); $translation->setTranslation($string); $writeHandle[] = $translation; } } } foreach ($writeHandles as $key => $writeHandle) { $output->writeln('<info>writing ' . $key . '</info>...'); $content = Po::toString($writeHandle); file_put_contents($this->outputDir . DIRECTORY_SEPARATOR . $key . '.po', $content); } $output->writeln('<info>done</info>'); }