本文整理汇总了PHP中SplFileObject::fputcsv方法的典型用法代码示例。如果您正苦于以下问题:PHP SplFileObject::fputcsv方法的具体用法?PHP SplFileObject::fputcsv怎么用?PHP SplFileObject::fputcsv使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SplFileObject
的用法示例。
在下文中一共展示了SplFileObject::fputcsv方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: writeRow
/**
* {@inheritdoc}
* @param array|Traversable $row The row to write
*/
public function writeRow($row)
{
if ($row instanceof \Traversable) {
$row = iterator_to_array($row);
}
$this->fileObject->fputcsv(is_array($row) ? $row : [$row]);
}
示例2: write
/**
* Converts all objects in a collection to CSV and saves them to the FILENAME constant of the collection
* @param string $path the base path to write to; e.g. 'gtfs/'
* @param mixed $collection A collection of GTFS objects
* @return void
*/
public static function write($path, $collection)
{
if ($collection->count()) {
$file = new \SplFileObject($path . $collection::FILENAME, 'w+');
$file->fputcsv(array_keys($collection->getFirst()->__toArray()));
foreach ($collection as $object) {
$file->fputcsv($object->__toArray());
}
}
}
示例3: insertOne
/**
* Adds a single line to a CSV document
*
* @param string[]|string $row a string, an array or an object implementing to '__toString' method
*
* @return static
*/
public function insertOne($row)
{
if (!is_array($row)) {
$row = str_getcsv($row, $this->delimiter, $this->enclosure, $this->escape);
}
$row = $this->formatRow($row);
$this->validateRow($row);
if (is_null($this->csv)) {
$this->csv = $this->getIterator();
}
$this->csv->fputcsv($row, $this->delimiter, $this->enclosure);
if ("\n" !== $this->newline) {
$this->csv->fseek(-1, SEEK_CUR);
$this->csv->fwrite($this->newline);
}
return $this;
}
示例4: putCSVRecord
/**
* フィールドの配列をCSVの行として書き出します。
* @param \SplFileObject $file
* @param string[] $fields
*/
protected function putCSVRecord(\SplFileObject $file, array $fields)
{
$file->fputcsv(array_map(function (string $field) : string {
return preg_replace('/[\\x00-\\x09\\x11\\x7F]+/u', '', strtr($field, ["\r\n" => "\r\n", "\r" => "\r\n", "\n" => "\r\n"]));
}, $fields));
$file->fseek(-1, SEEK_CUR);
$file->fwrite("\r\n");
}
示例5: _write
private function _write()
{
$this->_file->ftruncate(0);
foreach ($this->_data as $domain => $stats) {
foreach ($stats as $date => $row) {
$this->_file->fputcsv([$domain, $date] + $row);
}
}
}
示例6: postIndex
public function postIndex(Request $request)
{
// dump($request->input());
$faker = Faker::create();
$num_users = $request->input('num_users');
$address = $request->input('address');
if ($address == 'on') {
$this->formdata['address_yes'] = 'checked';
}
$phone = $request->input('phone');
if ($phone == 'on') {
$this->formdata['phone_yes'] = 'checked';
}
$photo = $request->input('photo');
if ($photo == 'on') {
$this->formdata['photo_yes'] = 'checked';
}
for ($i = 0; $i < $num_users; $i++) {
$users[$i]['name'] = $faker->name;
$users[$i]['username'] = "@" . $faker->username;
if ($i % 2 == 0) {
$fname = $faker->firstName;
$lname = $faker->lastName;
$email = strtolower(substr($fname, 0, 1)) . $lname . "@" . $faker->freeEmailDomain;
$users[$i]['name'] = $fname . " " . $lname;
$users[$i]['email'] = $email;
} else {
$users[$i]['email'] = $faker->email;
}
if ($address == 'on') {
$users[$i]['streetaddress'] = $faker->streetAddress;
$users[$i]['city'] = $faker->city;
$users[$i]['postcode'] = $faker->postcode;
$users[$i]['state'] = $faker->stateAbbr;
}
if ($phone == 'on') {
$users[$i]['phone'] = $faker->phoneNumber;
}
if ($photo == 'on') {
$users[$i]['photo'] = $faker->imageUrl($width = 200, $height = 200, 'animals');
}
}
$jsonpath = public_path();
$jsonpath .= '/downloads/randomusers.json';
$json = fopen($jsonpath, 'w');
fwrite($json, json_encode($users));
fclose($json);
$csv = new \SplFileObject('downloads/randomusers.csv', 'w');
foreach ($users as $user) {
$csv->fputcsv($user);
}
return view('user_generator')->with('users', $users)->with('formdata', $this->formdata);
}
示例7: export
public function export(TableView $view, $template = null, array $options = array())
{
$out = tempnam('/tmp', 'export-out-');
$data = $view->getData();
$file = new \SplFileObject($out, 'w');
$file->setCsvControl($this->delimiter, $this->enclosure, $this->escape);
$row = array();
foreach ($data['thead'] as $th) {
$row[] = $th['title'];
}
$file->fputcsv($row);
foreach ($data['tbody'] as $tr) {
$row = array();
foreach ($tr['data'] as $td) {
$row[] = $td['value'];
}
$file->fputcsv($row);
}
$now = new \DateTime();
$filename = preg_replace(array('/\\[now\\]/', '/\\[caption\\]/'), array($now->format('Y-m-d H\\hi'), $data['caption']), 'Export');
return new Export($file->getFileInfo(), $this->getContentType(), $filename, $this->getFileExtension());
}
示例8: SplFileObject
<?php
$fo = new SplFileObject(__DIR__ . '/SplFileObject_fputcsv1.csv', 'w');
$data = array(1, 2, 'foo', 'haha', array(4, 5, 6), 1.3, null);
$fo->fputcsv($data);
var_dump($data);
示例9: createMrpException
function createMrpException($itemKeyValues)
{
global $mrpExceptionDir, $isMrpHeaderAdded, $itemMasterFields, $itemDistributorFields, $mrpExcepFile;
if (!$isMrpHeaderAdded) {
$mrpExcepFile = new SplFileObject($mrpExceptionDir, 'w');
$mrpExcepFile->fputcsv(array_merge($itemMasterFields, $itemDistributorFields));
$isMrpHeaderAdded = true;
}
$mrpExcepFile->fputcsv($itemKeyValues);
}
示例10: generateTradeFileAction
public function generateTradeFileAction(Request $request)
{
$ria = $this->getUser();
/** @var RiaCompanyInformation $riaCompanyInformation */
$riaCompanyInformation = $ria->getRiaCompanyInformation();
$isHouseholdLevel = $riaCompanyInformation->isHouseholdManagedLevel();
$formValues = $request->get('rebalance_form');
$clientPortfolioValuesManager = $this->get('wealthbot_client.client_portfolio_values.manager');
$clientAccountValuesManager = $this->get('wealthbot_client.client_account_values.manager');
$clientPortfolioManager = $this->get('wealthbot_client.client_portfolio.manager');
$rebalancerQueueManager = $this->get('wealthbot.manager.rebalancer_queue');
if (isset($formValues['is_all']) && $formValues['is_all']) {
if ($isHouseholdLevel) {
$clientValues = $clientPortfolioValuesManager->getLatestClientPortfolioValuesForClients($ria);
} else {
$clientValues = $clientAccountValuesManager->getLatestClientAccountValuesForClients($ria, $clientPortfolioManager);
}
$clientValuesIds = array();
foreach ($clientValues as $clientValue) {
$clientValuesIds[] = $clientValue->getId();
}
} else {
$clientValuesIds = $formValues['client_value'];
}
if (!$request->isXmlHttpRequest() || empty($clientValuesIds)) {
throw $this->createNotFoundException();
}
$form = $this->createForm(new RebalanceFormType($clientValuesIds, true));
$form->bind($request);
if ($form->isValid()) {
$tradeDataCollection = $rebalancerQueueManager->getTradeDataCollection($riaCompanyInformation, $clientValuesIds);
if (empty($tradeDataCollection)) {
return $this->getJsonResponse(array('status' => 'error', 'message' => 'No Trades'));
}
$date = date('mdY-His');
$filename = $date . '.csv';
$filePath = $this->container->getParameter('uploads_trade_files_dir') . '/' . $filename;
$file = new \SplFileObject($filePath, 'w');
foreach ($tradeDataCollection as $tradeData) {
$file->fputcsv($tradeData->toArrayForTradeFile());
if ($tradeData->getAction() === RebalancerQueue::STATUS_SELL) {
foreach ($tradeData->getVsps() as $vsp) {
$file->fputcsv($vsp);
}
}
}
return $this->getJsonResponse(array('status' => 'success', 'redirect_url' => $this->generateUrl('rx_download_trade_file', array('filename' => $filename))));
}
return $this->getJsonResponse(array('status' => 'error', 'message' => 'Invalid Data'));
}
示例11: while
$s1->setFlags(SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
if ($s1->isFile() && $s1->isReadable()) {
$s1->seek(1);
while ($row = $s1->fgetcsv($delimieter[0])) {
$data = array($row[7], $row[8]);
if (!in_array($data, $values)) {
$values[] = $data;
}
}
unset($row);
usort($values, function ($a, $b) {
return $a[0] > $b[0];
});
try {
$s2 = new SplFileObject($argv[2], 'w');
$s2->fputcsv(array('id', 'code'), $delimieter[1]);
foreach ($values as $data) {
$s2->fputcsv($data, "\t");
}
} catch (RuntimeException $e) {
echo $e->getMessage();
exit($e->severity);
} finally {
unset($s2);
}
unset($data, $values);
}
} catch (RuntimeException $e) {
echo $e->getMessage();
exit($e->severity);
}
示例12: create
/**
* Tries to create the file.
*
* If it already exists - throw an exception.
* After creating it puts into file row with column headers.
*
* @param $filename
* @param $fileConfig
* @param null $delimiter
* @return bool
* @throws \Exception
*/
public function create($filename, $fileConfig, $delimiter = null)
{
if ($this->has($filename)) {
throw new \Exception("The file \"{$filename}\" already exists. Use \"rewrite()\" instead.");
}
$filename = $this->getRealFileName($filename);
$delimiter = !is_null($delimiter) ?: self::DELIMITER_BY_DEFAULT;
try {
$file = new \SplFileObject($filename, 'w');
$file->fputcsv($fileConfig, $delimiter);
} catch (\Exception $e) {
return false;
} finally {
// Close file
unset($file);
// Make garbage the cycle that the closing file was done immediately.
gc_collect_cycles();
}
return true;
}
示例13: array
<?php
$dados = array(array('codigo', 'nome', 'endereco', 'telefone'), array('1', 'Maria da Silva', 'Rua da Maria', '(11) 12345678'), array('2', 'Pedro Cardoso', 'Rua do Pedro', '(11) 12345678'), array('3', 'Joana Pereira', 'Rua da Joana', '(11) 12345678'));
$file = new SplFileObject('dados.csv', 'w');
$file->setCsvControl(',');
foreach ($dados as $linha) {
$file->fputcsv($linha);
}
示例14: postIndex
/**
* Responds to requests to POST /users
*/
public function postIndex(Request $request)
{
$faker = Faker::create();
$this->validate($request, ['numusers' => 'required|numeric|min:1|max:10']);
$numusers = $request->input('numusers');
$this->formdata['numusers'] = $numusers;
$address = $request->input('address');
if ($address == 'on') {
$this->formdata['addressyes'] = 'checked';
}
$phone = $request->input('phone');
if ($phone == 'on') {
$this->formdata['phoneyes'] = 'checked';
}
$birthday = $request->input('birthday');
if ($birthday == 'on') {
$this->formdata['birthdayyes'] = 'checked';
}
$profile = $request->input('profile');
if ($profile == 'on') {
$this->formdata['profileyes'] = 'checked';
}
$photo = $request->input('photo');
if ($photo == 'on') {
$this->formdata['photoyes'] = 'checked';
}
for ($i = 0; $i < $numusers; $i++) {
$users[$i]['name'] = $faker->name;
$users[$i]['username'] = $faker->username;
$users[$i]['email'] = $faker->email;
if ($address == 'on') {
$users[$i]['streetaddress'] = $faker->streetAddress;
$users[$i]['city'] = $faker->city;
$users[$i]['postcode'] = $faker->postcode;
$users[$i]['state'] = $faker->stateAbbr;
}
if ($phone == 'on') {
$users[$i]['phone'] = $faker->phoneNumber;
}
if ($birthday == 'on') {
/*
note: setting minimum age of fake users to 13
to avoid COPPA complications: http://www.coppa.org/
*/
$users[$i]['birthday'] = $faker->date($format = 'Y-m-d', $max = '2002-10-21');
}
if ($profile == 'on') {
$users[$i]['profile'] = $faker->text($maxNbChars = 140);
}
if ($photo == 'on') {
$users[$i]['photo'] = $faker->imageUrl($width = 200, $height = 200, 'cats');
}
}
$json = fopen('downloads/randomusers.json', 'w');
fwrite($json, json_encode($users));
fclose($json);
$csv = new \SplFileObject('downloads/randomusers.csv', 'w');
foreach ($users as $user) {
$csv->fputcsv($user);
}
return view('users')->with('users', $users)->with('formdata', $this->formdata);
}
示例15: die
$export_query .= $_SESSION['where'];
$export_result = mysqli_query($dbc, $export_query) or die('Error querying database.');
if (isset($_POST['csv_export'])) {
// ファイル名
$file_path = '../../tmp/user_list.csv';
// CSVに出力するタイトル行
$export_csv_title = array('No.', '姓', '名', 'メールアドレス', 'ユーザID', 'パスワード', '生年月日', '性別');
if (touch($file_path)) {
// オブジェクト生成
$file = new SplFileObject($file_path, 'w');
// タイトル行のエンコードをSJIS-winに変換
foreach ($export_csv_title as $key => $val) {
$export_header[] = mb_convert_encoding($val, 'SJIS-win', 'UTF-8');
}
// エンコードしたタイトル行を配列ごとCSVデータ化
$file->fputcsv($export_header);
while ($row_export = mysqli_fetch_assoc($export_result)) {
$export_arr = '';
// 内容行のエンコードをSJIS-winに変換
foreach ($row_export as $key => $val) {
$export_arr[] = mb_convert_encoding($val, 'SJIS-win', 'UTF-8');
}
// エンコードした内容行を配列ごとCSVデータ化
$file->fputcsv($export_arr);
}
}
// ダウンロード
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Cache-Control: private', false);