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


PHP fputcsv函数代码示例

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


在下文中一共展示了fputcsv函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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 yugang@ymt360.com
  * @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


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