本文整理汇总了PHP中fputcsv函数的典型用法代码示例。如果您正苦于以下问题:PHP fputcsv函数的具体用法?PHP fputcsv怎么用?PHP fputcsv使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了fputcsv函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。
示例1: execute
protected function execute(InputInterface $input, OutputInterface $output)
{
$path = $input->getArgument('path');
if (!file_exists($path)) {
$output->writeln("{$path} is not a file or a path");
}
$filePaths = [];
if (is_file($path)) {
$filePaths = [realpath($path)];
} elseif (is_dir($path)) {
$filePaths = array_diff(scandir($path), array('..', '.'));
} else {
$output->writeln("{$path} is not known.");
}
$generator = new StopwordGenerator($filePaths);
if ($input->getArgument('type') === 'json') {
echo json_encode($this->toArray($generator->getStopwords()), JSON_NUMERIC_CHECK | JSON_UNESCAPED_UNICODE);
echo json_last_error_msg();
die;
$output->write(json_encode($this->toArray($generator->getStopwords())));
} else {
$stopwords = $generator->getStopwords();
$stdout = fopen('php://stdout', 'w');
echo 'token,freq' . PHP_EOL;
foreach ($stopwords as $token => $freq) {
fputcsv($stdout, [utf8_encode($token), $freq]) . PHP_EOL;
}
fclose($stdout);
}
}
开发者ID:yooper,项目名称:php-text-analysis,代码行数:30,代码来源:StopWordsCommand.php
示例2: createCSV
public function createCSV($selectedName)
{
// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=HRdata.csv');
// create a file pointer connected to the output stream
$file = fopen('php://output', 'w');
// Connect to the DB
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "rfid_database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Fetch the data
$sql = "SELECT users.userName, nomenclature.nomenclature_Name, locations.roomNumber, makes.makeName, models.model_Name, items.rfid, items.serialNum FROM items join locations on items.location_id=locations.location_id join models on items.model_id=models.model_id join nomenclature on nomenclature.nomenclature_id=models.nom_id join makes on models.make_id=makes.make_id join users on users.user_id=items.hrholder_id WHERE userName like '%{$selectedName}%'";
$result = $conn->query($sql);
// Headers for the file
fputcsv($file, array('Nomenclature', 'Count', 'Location', 'Make', 'Model', 'Serial Number', 'RFID'));
// Place the data in the file
if ($result->num_rows > 0) {
// output data of each row
while ($row = $result->fetch_assoc()) {
fputcsv($file, array($row["nomenclature_Name"], "Count Holder", $row["roomNumber"], $row["makeName"], $row["model_Name"], $row["rfid"], $row["serialNum"]));
}
}
fclose($file);
}
开发者ID:Notacadet,项目名称:RFID,代码行数:27,代码来源:ExportCSV.php
示例3: writeToCsvFileHandle
/**
* This function can be used to write the csv directly into a file handle
* (e.g. STDOUT). It's will be called by `saveToCsvFile`.
*/
public function writeToCsvFileHandle($file_handle)
{
$rows = self::extractAllDescendants($this->root, $this->field_mappings);
foreach ($rows as $row) {
fputcsv($file_handle, $row, ';');
}
}
开发者ID:dracoblue,项目名称:craur,代码行数:11,代码来源:CraurCsvWriter.php
示例4: process
function process()
{
global $dbh;
$data = array('Order ID');
foreach ($this->formbuilder->_questions as $question) {
$data[] = $question->qkey;
}
if (empty($data)) {
error_exit('No survey details available for download.');
}
header('Content-type: text/x-csv');
header("Content-Disposition: attachment; filename=\"{$this->event->name}_survey.csv\"");
$out = fopen('php://output', 'w');
fputcsv($out, $data);
$sth = $dbh->prepare('SELECT order_id FROM registrations r WHERE r.registration_id = ? ORDER BY order_id');
$sth->execute(array($this->event->registration_id));
while ($row = $sth->fetch()) {
$data = array(sprintf(variable_get('order_id_format', '%d'), $row['order_id']));
// Add all of the answers
$fsth = $dbh->prepare('SELECT akey FROM registration_answers WHERE order_id = ? AND qkey = ?');
foreach ($this->formbuilder->_questions as $question) {
$fsth->execute(array($row['order_id'], $question->qkey));
$foo = $fsth->fetchColumn();
$data[] = preg_replace('/\\s\\s+/', ' ', $foo);
}
fputcsv($out, $data);
}
fclose($out);
exit;
}
开发者ID:roboshed,项目名称:leaguerunner,代码行数:30,代码来源:downloadsurvey.php
示例5: outToExcel
public function outToExcel()
{
// 输出Excel文件头,可把user.csv换成你要的文件名
header("Content-type:text/csv");
header('Content-Disposition: attachment;filename="company.csv"');
header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
header('Expires:0');
header('Pragma:public');
// 从数据库中获取数据,为了节省内存,不要把数据一次性读到内存,从句柄中一行一行读即可
$m = M('Company_try_eat');
$result = $m->select();
// 打开PHP文件句柄,php://output 表示直接输出到浏览器
$fp = fopen('php://output', 'a');
// 输出Excel列名信息
$head = array('企业名称', '城市', '区域', '地址', '试吃部门', '人数', '试吃时间', '企业需求', '联系人', '职位', '办公电话', '手机', '邮箱', '留言', '申请日期');
foreach ($head as $i => $v) {
// CSV的Excel支持GBK编码,一定要转换,否则乱码
$head[$i] = iconv('utf-8', 'gbk', $v);
}
//将数据通过fputcsv写到文件句柄
fputcsv($fp, $head);
// 计数器
$cnt = 0;
// 每隔$limit行,刷新一下输出buffer,不要太大,也不要太小
$limit = 100000;
// 逐行取出数据,不浪费内存
for ($j = 0; $j < count($result); $j++) {
$row = $result[$j];
$info = array(iconv('utf-8', 'gbk', $row['companyName']), iconv('utf-8', 'gbk', $row['companyCity']), iconv('utf-8', 'gbk', $row['companyArea']), iconv('utf-8', 'gbk', $row['companyAddress']), iconv('utf-8', 'gbk', $row['companyDepartment']), iconv('utf-8', 'gbk', $row['eatPeople']), iconv('utf-8', 'gbk', $row['eatTimerand']), iconv('utf-8', 'gbk', $row['companyDemand']), iconv('utf-8', 'gbk', $row['userName']), iconv('utf-8', 'gbk', $row['userPosition']), iconv('utf-8', 'gbk', $row['userTel']), iconv('utf-8', 'gbk', $row['userMobile']), iconv('utf-8', 'gbk', $row['userEmail']), iconv('utf-8', 'gbk', $row['userMessage']), iconv('utf-8', 'gbk', $row['addTime']));
fputcsv($fp, $info);
}
}
开发者ID:superSN,项目名称:alexander,代码行数:32,代码来源:CompanyAction.class.php
示例6: csv
/**
* export data to csv file
*
* @param <type> $_args The arguments
* @param $_arg['name'] [name of file]
* @param $_arg['type'] [type of file]
* @param $_arg['data'] [data to export]
*/
public static function csv($_args)
{
$type = isset($_args['type']) ? $_args['type'] : 'csv';
$filename = isset($_args['name']) ? $_args['name'] : 'Untitled';
$data = $_args['data'];
// disable caching
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
// disposition / encoding on response body
header("Content-Disposition: attachment;filename={$filename}.{$type}");
header("Content-Transfer-Encoding: binary");
if (count($data) == 0 || !$data || empty($data)) {
echo null;
// die();
}
ob_start();
$df = fopen("php://output", 'w');
fputcsv($df, array_keys(reset($data)));
foreach ($data as $row) {
fputcsv($df, $row);
}
fclose($df);
echo ob_get_clean();
die;
}
开发者ID:Ermile,项目名称:Saloos,代码行数:37,代码来源:export.php
示例7: export_csv
/**
* 导出csv数据报表
* @author [email protected]
* @since 2015-01-30
*/
public function export_csv($title_arr, $data, $file_path = 'default.csv')
{
array_unshift($data, $title_arr);
// 在公共的方法中使用导出时间不限制
// 以防止数据表太大造成csv文件过大,造成超时
set_time_limit(0);
$temp_file_path = BASEPATH . '../application/temp/' . uniqid() . '.csv';
$file = fopen($temp_file_path, 'w');
$keys = array_keys($title_arr);
foreach ($data as $item) {
// 对数组中的内容按照标题的顺序排序,去除不需要的内容
$info = array();
foreach ($keys as $v) {
$info[$v] = isset($item[$v]) ? $item[$v] : '';
}
fputcsv($file, $info);
}
fclose($file);
//在win下看utf8的csv会有点问题
$str = file_get_contents($temp_file_path);
$str = iconv('UTF-8', 'GBK', $str);
unlink($temp_file_path);
// 下载文件
$this->load->helper('download');
force_download($file_path, $str);
}
开发者ID:OranTing,项目名称:gdby_github_repo,代码行数:31,代码来源:MY_Controller.php
示例8: authControl
public function authControl()
{
if ($this->is_missing_param) {
echo 'No search data to export.';
} else {
if (get_magic_quotes_gpc()) {
$_POST['grid_export_data'] = stripslashes($_POST['grid_export_data']);
}
$data = json_decode($_POST['grid_export_data']);
if (!$data) {
echo 'No search data to export.' . json_last_error() . "<br />";
echo $_POST['grid_export_data'];
} else {
if (!headers_sent()) {
// this is so our test don't barf on us
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export.csv"');
header('Pragma: no-cache');
header('Expires: 0');
}
$fp = fopen('php://output', 'w');
foreach ($data as $post) {
// output post csv line
fputcsv($fp, (array) $post);
// flush output buffer
flush();
}
// close output handle
fclose($fp);
}
}
}
开发者ID:dgw,项目名称:ThinkUp,代码行数:32,代码来源:class.GridExportController.php
示例9: backupChannelAction
public function backupChannelAction()
{
$channel = $_GET['channel'];
$channelStripped = preg_replace("/[^[:alnum:][:space:]]/ui", '', $channel);
$filename = "WiseChatChannelBackup-{$channelStripped}.csv";
$now = gmdate("D, d M Y H:i:s");
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$now} GMT");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
$messages = $this->messagesService->getAllByChannelName($channel);
ob_start();
$df = fopen("php://output", 'w');
fputcsv($df, array('ID', 'Time', 'User', 'Message', 'IP'));
foreach ($messages as $message) {
$messageArray = array($message->getId(), date("Y-m-d H:i:s", $message->getTime()), $message->getUserName(), $message->getText(), $message->getIp());
fputcsv($df, $messageArray);
}
fclose($df);
echo ob_get_clean();
die;
}
开发者ID:andyUA,项目名称:kabmin-new,代码行数:26,代码来源:WiseChatChannelsTab.php
示例10: flush
/**
* {@inheritdoc}
*
* Override of CsvWriter flush method to use the file buffer
*/
public function flush()
{
if (!is_file($this->bufferFile)) {
return;
}
$exportDirectory = dirname($this->getPath());
if (!is_dir($exportDirectory)) {
$this->localFs->mkdir($exportDirectory);
}
$this->writtenFiles[$this->getPath()] = basename($this->getPath());
if (false === ($csvFile = fopen($this->getPath(), 'w'))) {
throw new RuntimeErrorException('Failed to open file %path%', ['%path%' => $this->getPath()]);
}
$header = $this->isWithHeader() ? $this->headers : [];
if (false === fputcsv($csvFile, $header, $this->delimiter)) {
throw new RuntimeErrorException('Failed to write to file %path%', ['%path%' => $this->getPath()]);
}
$bufferHandle = fopen($this->bufferFile, 'r');
$hollowProduct = array_fill_keys($this->headers, '');
while (null !== ($bufferedProduct = $this->readProductFromBuffer($bufferHandle))) {
$fullProduct = array_replace($hollowProduct, $bufferedProduct);
if (false === fputcsv($csvFile, $fullProduct, $this->delimiter, $this->enclosure)) {
throw new RuntimeErrorException('Failed to write to file %path%', ['%path%' => $this->getPath()]);
} elseif (null !== $this->stepExecution) {
$this->stepExecution->incrementSummaryInfo('write');
}
}
fclose($bufferHandle);
unlink($this->bufferFile);
fclose($csvFile);
}
开发者ID:VinceBLOT,项目名称:pim-community-dev,代码行数:36,代码来源:CsvProductWriter.php
示例11: writeToFile
/**
* write data to file (csv)
* @global boolean $export
* @global file pointer $fp
* @param array $data
*/
function writeToFile($data)
{
global $export, $fp;
if ($export) {
fputcsv($fp, $data);
}
}
开发者ID:Tjorriemorrie,项目名称:app,代码行数:13,代码来源:getVideoMetadata.php
示例12: run
public function run($args)
{
$f = fopen(self::DUMP_FILE, 'a+');
if (!$f) {
die('Failed to open ' . self::DUMP_FILE . " for writing\n");
}
$db = Yii::app()->db;
$cmd = $db->createCommand()->select('a.*')->from('address a')->leftJoin('contact c', "a.parent_class = 'Contact' and a.parent_id = c.id")->where('c.id is null')->limit(self::BATCH_SIZE);
while (1) {
$tx = $db->beginTransaction();
if (!($rows = $cmd->queryAll())) {
$tx->commit();
break;
}
echo 'Deleting ' . count($rows) . " rows...\n";
$ids = array();
foreach ($rows as $row) {
if (!fputcsv($f, $row)) {
die("Failed to write CSV row\n");
}
$ids[] = $row['id'];
}
if (!fflush($f)) {
die('Flush failed');
}
$db->createCommand()->delete('address', array('in', 'id', $ids));
$tx->commit();
sleep(1);
}
fclose($f);
echo "Done\n";
}
开发者ID:openeyes,项目名称:openeyes,代码行数:32,代码来源:CleanupAddressesCommand.php
示例13: _outputRow
protected function _outputRow(array $row)
{
if ($this->isConvertEncoding === true) {
$this->_convertEncoding($row);
}
fputcsv($this->outstream, $row, $this->delimiter, $this->enclosure);
}
开发者ID:nouphet,项目名称:xoops-tpSocialMedia,代码行数:7,代码来源:CsvExport.php
示例14: write_csv_line
function write_csv_line($fileName, $path)
{
global $ftpServer, $ftpUsername, $ftpPassword, $tags, $contentType, $fileResource;
$url = "ftp://{$ftpUsername}:{$ftpPassword}@{$ftpServer}{$path}";
$line = array($fileName, $fileName, $tags, $url, $contentType);
fputcsv($fileResource, $line);
}
开发者ID:DBezemer,项目名称:server,代码行数:7,代码来源:bulkScvFromFtp.php
示例15: process_csv_file
function process_csv_file($file_name, $output_file_name, $zip_column)
{
global $zip_code_state_ranges;
$file_handle = fopen($file_name, "r") or die("Couldn't open {$file_name}\n");
$output_file_handle = fopen($output_file_name, "w") or die("Couldn't open {$output_file_name}\n");
$line_index = 0;
while (!feof($file_handle)) {
$current_parts = fgetcsv($file_handle, 0);
$naked_zip = $current_parts[$zip_column];
$full_zip = '';
foreach ($zip_code_state_ranges as $state => $ranges) {
foreach ($ranges as $range) {
$start = $range[0];
$end = $range[1];
if ($naked_zip >= $start && $naked_zip <= $end) {
$full_zip = $state . " " . $naked_zip;
break;
}
}
}
$current_parts[$zip_column] = $full_zip;
fputcsv($output_file_handle, $current_parts);
}
fclose($file_handle);
fclose($output_file_handle);
}
开发者ID:nateforsyth,项目名称:openheatmap,代码行数:26,代码来源:addzip.php
示例16: rotate
/**
* Rotate logs - get from database and pump to CSV-file
*
* @param int $lifetime
*/
public function rotate($lifetime)
{
// $this->beginTransaction();
// try {
$readAdapter = $this->_getReadAdapter();
$writeAdapter = $this->_getWriteAdapter();
$table = $this->getTable('enterprise_logging/event');
// get the latest log entry required to the moment
$clearBefore = $this->formatDate(time() - $lifetime);
$select = $readAdapter->select()->from($this->getMainTable(), 'log_id')->where('time < ?', $clearBefore)->order('log_id DESC')->limit(1);
$latestLogEntry = $readAdapter->fetchOne($select);
if ($latestLogEntry) {
// make sure folder for dump file will exist
$archive = Mage::getModel('enterprise_logging/archive');
$archive->createNew();
$expr = Mage::getResourceHelper('enterprise_logging')->getInetNtoaExpr('ip');
$select = $readAdapter->select()->from($this->getMainTable())->where('log_id <= ?', $latestLogEntry)->columns($expr);
$rows = $readAdapter->fetchAll($select);
// dump all records before this log entry into a CSV-file
$csv = fopen($archive->getFilename(), 'w');
foreach ($rows as $row) {
fputcsv($csv, $row);
}
fclose($csv);
$writeAdapter->delete($this->getMainTable(), array('log_id <= ?' => $latestLogEntry));
// $this->commit();
}
// } catch (Exception $e) {
// $this->rollBack();
// }
}
开发者ID:hyhoocchan,项目名称:mage-local,代码行数:36,代码来源:Event.php
示例17: generate
/**
* Generates a CSV string from given array data
*
* @param array $data
*
* @throws \RuntimeException
*
* @return string
*/
public function generate(array $data)
{
$fileHandle = fopen('php://temp', 'w');
if (!$fileHandle) {
throw new \RuntimeException("Cannot open temp file handle (php://temp)");
}
if (!is_array($data[0])) {
$data = [$data];
}
$tmpPlaceholder = 'MJASCHEN_COLLMEX_WORKAROUND_PHP_BUG_43225_' . time();
foreach ($data as $line) {
// workaround for PHP bug 43225: temporarily insert a placeholder
// between a backslash directly followed by a double-quote (for
// string field values only)
array_walk($line, function (&$item) use($tmpPlaceholder) {
if (!is_string($item)) {
return;
}
$item = preg_replace('/(\\\\+)"/m', '$1' . $tmpPlaceholder . '"', $item);
});
fputcsv($fileHandle, $line, $this->delimiter, $this->enclosure);
}
rewind($fileHandle);
$csv = stream_get_contents($fileHandle);
fclose($fileHandle);
// remove the temporary placeholder from the final CSV string
$csv = str_replace($tmpPlaceholder, '', $csv);
return $csv;
}
开发者ID:mjaschen,项目名称:collmex,代码行数:38,代码来源:SimpleGenerator.php
示例18: export
/**
* export to csv
*/
public function export()
{
$this->import('Database');
//IE or other?
$log_version = '';
$HTTP_USER_AGENT = getenv("HTTP_USER_AGENT");
if (preg_match('@MSIE ([0-9].[0-9]{1,2})@', $HTTP_USER_AGENT, $log_version)) {
$this->BrowserAgent = 'IE';
} else {
$this->BrowserAgent = 'NOIE';
}
// send header
header('Content-Type: text/comma-separated-values');
header('Expires: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Content-Disposition: attachment; filename="SearchKeys-' . date('d.m.Y') . '.utf8.csv"');
if ($this->BrowserAgent == 'IE') {
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
} else {
header('Pragma: no-cache');
}
// send data
$objSearchKeys = $this->Database->prepare("SELECT FROM_UNIXTIME(tstamp),searchkey,results,relevance FROM tl_om_searchkeys ORDER BY tstamp DESC")->execute();
if ($objSearchKeys->numRows) {
$arrSearchKeys = $objSearchKeys->fetchAllAssoc();
}
$out = fopen('php://output', 'w');
fputcsv($out, array('Zeit', 'Keyword', 'Ergebnisse', 'Relevance (Durchschnitt)'), ',');
foreach ($arrSearchKeys as $value) {
fputcsv($out, $value, ',');
}
fclose($out);
exit;
}
开发者ID:omosde,项目名称:om_searchkeys,代码行数:37,代码来源:ModuleOmSearchKeys.php
示例19: xmlTocsv
/**
* Function to use two step to built the cvs file, one row for the title
* othter rows for the data.
*/
function xmlTocsv($xml_path)
{
$xml = simplexml_load_file($xml_path);
$title_list = array();
foreach ($xml as $key => $product) {
foreach ($product as $name => $value) {
array_push($product_property_list, $name);
}
break;
// only need one loop to get the all titles
}
$process_array = array();
foreach ($xml as $key => $product) {
$temp_array = array();
foreach ($product as $name) {
array_push($temp_array, "{$name}");
}
array_push($process_array, $temp_array);
}
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="sample.csv"');
$fp = fopen('php://output', 'w');
// insert the title of csv each column
fputcsv($fp, $title_list);
foreach ($process_array as $product) {
// insert the data of the csv
fputcsv($fp, $product);
}
fclose($fp);
}
开发者ID:vincentywang,项目名称:code_collection,代码行数:34,代码来源:xml_to_csv.php
示例20: display
/**
* Return statistics CSV file
*
* @param string $tpl The name of the template file to parse; automatically searches through the template paths.
*
* @return void
*/
function display($tpl = null)
{
$this->item = $this->get('Item');
// Get parameters
$jinput = JFactory::getApplication()->input;
$type = $jinput->get('type', null, 'string');
$begin = $jinput->get('begin', null, 'string');
$end = $jinput->get('end', null, 'string');
// Convert date strings to JDate objects
$beginDate = new JDate($begin);
$endDate = new JDate($end . ' 23:59:59');
// Get statistic model
$statisticModel = JModelLegacy::getInstance('statistic', 'IssnregistryModel');
// Get statistics
$csv = $statisticModel->getStats($type, $beginDate, $endDate);
// Set document properties
$document = JFactory::getDocument();
$document->setMimeEncoding('text/csv; charset="UTF-8"');
JResponse::setHeader('Content-disposition', 'attachment; filename="statistics.csv"', true);
// Write to output
$out = fopen('php://output', 'w');
// Loop through CSV data and write each row to output
foreach ($csv as $row) {
// Columns are tab separated
fputcsv($out, $row, "\t");
}
// Close output
fclose($out);
}
开发者ID:petkivim,项目名称:id-registry,代码行数:36,代码来源:view.csv.php
注:本文中的fputcsv函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论