当前位置: 首页>>代码示例>>PHP>>正文


PHP Csv\Reader类代码示例

本文整理汇总了PHP中League\Csv\Reader的典型用法代码示例。如果您正苦于以下问题:PHP Reader类的具体用法?PHP Reader怎么用?PHP Reader使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Reader类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: render

 protected function render()
 {
     $fileObject = new \SplFileObject($this->getPath());
     $reader = Reader::createFromFileObject($fileObject);
     $reader->setFlags(\SplFileObject::READ_AHEAD | \SplFileObject::SKIP_EMPTY);
     return $reader;
 }
开发者ID:GreenHackers,项目名称:geo-endpoint,代码行数:7,代码来源:AbstractReader.php

示例2: 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);
 }
开发者ID:phillipmadsen,项目名称:datatableplus,代码行数:40,代码来源:DataTablePlus.php

示例3: execute

 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->promptForCredentials($input, $output);
     $dstPath = $input->getArgument('dst_path');
     $csvPath = $input->getArgument('csv_path');
     $reader = new Reader($csvPath);
     $csv = $reader->setOffset(1)->fetchAll();
     // Create destination folder.
     mkdir($dstPath, 0777, true);
     if (!is_writeable($dstPath)) {
         die("OMERGERD COULDN'T WRITE TO DIRECTORY!!!");
     }
     foreach ($csv as $row) {
         list($sslId, $cn, $status) = array($row[0], $row[2], $row[4]);
         if ($status != 'Issued') {
             $output->writeln(sprintf("<info>%s is %s. Skipping...</info>", $cn, $status));
             continue;
         }
         $output->writeln(sprintf("%s (%s): %s", $cn, $sslId, $status));
         $response = $this->incommon->certs->collect($this->authData, $sslId, 1);
         // Get cert contents.
         $certData = $response->SSL->certificate;
         // Clean * out of CN
         $filename = str_replace('*', 'star', $cn);
         // Write file
         $filepath = "{$dstPath}/{$filename}.crt";
         $fp = fopen($filepath, "w");
         fwrite($fp, $certData);
         fclose($fp);
     }
 }
开发者ID:mdwheele,项目名称:incommon-cli,代码行数:31,代码来源:CollectCertCommand.php

示例4: __construct

 /**
  * @param Reader $reader
  */
 public function __construct(Reader $reader)
 {
     $tweets = [];
     foreach ($reader->fetchAssoc() as $tweet) {
         $tweets[] = new Tweet($this->getFrom($tweet, 'tweet_id'), $this->getFrom($tweet, 'text'), $this->getFrom($tweet, 'source'), $this->getFrom($tweet, 'timestamp'), $this->getFrom($tweet, 'in_reply_to_status_id'), $this->getFrom($tweet, 'retweeted_status_id'), $this->getFrom($tweet, 'expanded_urls'));
     }
     $this->tweetCollection = new TweetCollection($tweets);
 }
开发者ID:dotzecker,项目名称:tuiter,代码行数:11,代码来源:Tuiter.php

示例5: setDefaultsFromFile

 /**
  * Set the metadata from a file.
  *
  * @param string $file
  */
 public function setDefaultsFromFile($file)
 {
     $file = new Reader($file);
     // Fetch columns
     $rows = $file->fetchOne();
     $file->setOffset(1);
     // Fetch entries and set defaults
     $entries = $file->fetchAssoc($rows);
     foreach ($entries as $entry) {
         if (strpos(URL::current(), $entry['url']) !== false) {
             $this->defaults = $entry;
         }
     }
 }
开发者ID:anahkiasen,项目名称:arrounded,代码行数:19,代码来源:Metadata.php

示例6: 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();
 }
开发者ID:robotomize,项目名称:squadron-td-calc,代码行数:32,代码来源:DataParser.php

示例7: createImportEntries

 /**
  * Run the actual import
  *
  * @return Collection
  */
 public function createImportEntries() : Collection
 {
     $config = $this->job->configuration;
     $content = $this->job->uploadFileContents();
     // create CSV reader.
     $reader = Reader::createFromString($content);
     $reader->setDelimiter($config['delimiter']);
     $start = $config['has-headers'] ? 1 : 0;
     $results = $reader->fetch();
     Log::notice('Building importable objects from CSV file.');
     foreach ($results as $index => $row) {
         if ($index >= $start) {
             $line = $index + 1;
             Log::debug('----- import entry build start --');
             Log::debug(sprintf('Now going to import row %d.', $index));
             $importEntry = $this->importSingleRow($index, $row);
             $this->collection->put($line, $importEntry);
             /**
              * 1. Build import entry.
              * 2. Validate import entry.
              * 3. Store journal.
              * 4. Run rules.
              */
             $this->job->addTotalSteps(4);
             $this->job->addStepsDone(1);
         }
     }
     Log::debug(sprintf('Import collection contains %d entries', $this->collection->count()));
     Log::notice(sprintf('Built %d importable object(s) from your CSV file.', $this->collection->count()));
     return $this->collection;
 }
开发者ID:roberthorlings,项目名称:firefly-iii,代码行数:36,代码来源:CsvImporter.php

示例8: 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);
 }
开发者ID:netsensei,项目名称:resin,代码行数:31,代码来源:importArtists.php

示例9: 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);
         }
     }
 }
开发者ID:dobidobz,项目名称:HRis,代码行数:37,代码来源:ImportEmployeeList.php

示例10: 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);
 }
开发者ID:netsensei,项目名称:resin,代码行数:38,代码来源:importDocuments.php

示例11: 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;
 }
开发者ID:urukalo,项目名称:csvimporter,代码行数:35,代码来源:cvsImporter.php

示例12: 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);
 }
开发者ID:Hipp04,项目名称:registered-solutions,代码行数:32,代码来源:SchoolDataTransfer.php

示例13: 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');
 }
开发者ID:KaplanDigitalMarketing,项目名称:Timetables,代码行数:37,代码来源:DateController.php

示例14: postCsv

 /**
  * @param \Seat\Web\Http\Validation\CsvImport $request
  *
  * @return \Illuminate\Http\RedirectResponse
  */
 public function postCsv(CsvImport $request)
 {
     $csv = Reader::createFromFileObject($request->file('csv')->openFile());
     // Keep tabs on the amount of keys that have
     // been inserted, and how many have been
     // considered erroneous
     $updated = 0;
     $errored = 0;
     // Loop the CSV, validating the lines
     // and inserting into the database
     foreach ($csv as $k => $data) {
         // Assign the $data to readable names
         $key_id = $data[0];
         $v_code = $data[1];
         // Validate the keys. We check that we dont
         // already have this key in the database to ensure
         // that we dont mess up the ownership by accident.
         $validator = Validator::make(['key_id' => $key_id, 'v_code' => $v_code], ['key_id' => 'required|numeric|unique:eve_api_keys,key_id', 'v_code' => 'required|size:64|alpha_num']);
         // Ensure the format was ok
         if ($validator->fails()) {
             $errored++;
             continue;
         }
         // Add the API Key
         ApiKey::create(['key_id' => $key_id, 'v_code' => $v_code, 'user_id' => auth()->user()->id, 'enabled' => true]);
         $updated++;
     }
     return redirect()->back()->with('success', 'Import complete! Success: ' . $updated . '. Error: ' . $errored);
 }
开发者ID:eveseat,项目名称:web,代码行数:34,代码来源:ImportController.php

示例15: readCSV

 protected function readCSV()
 {
     $csvObj = Reader::createFromString($this->readFile(static::IMPORT_FILE));
     $csvObj->setDelimiter(',');
     $results = $csvObj->fetchAssoc();
     return $results;
 }
开发者ID:firegento,项目名称:FireGento_FastSimpleImport2_Demo,代码行数:7,代码来源:ImportCsv.php


注:本文中的League\Csv\Reader类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。