Пример #1
1
 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 = "******";
     $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);
 }
Пример #2
1
 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);
     }
 }
Пример #3
0
 /**
  * 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, ';');
     }
 }
Пример #4
0
 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;
 }
Пример #5
0
 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);
     }
 }
Пример #6
0
 /**
  * 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;
 }
Пример #7
0
 /**
  * 导出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);
 }
Пример #8
0
 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);
         }
     }
 }
Пример #9
0
 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;
 }
 /**
  * {@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);
 }
Пример #11
0
/**
 * 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);
    }
}
Пример #12
0
 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";
 }
Пример #13
0
 protected function _outputRow(array $row)
 {
     if ($this->isConvertEncoding === true) {
         $this->_convertEncoding($row);
     }
     fputcsv($this->outstream, $row, $this->delimiter, $this->enclosure);
 }
Пример #14
0
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);
}
Пример #15
0
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);
}
Пример #16
0
 /**
  * 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();
     //        }
 }
Пример #17
0
 /**
  * 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;
 }
Пример #18
0
 /**
  * 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;
 }
Пример #19
0
/**
 * 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);
}
Пример #20
0
 /**
  * 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);
 }
Пример #21
0
 public function test5Transactions()
 {
     $inputFile = fopen('php://memory', 'w+');
     $outputFile = fopen('php://memory', 'w+');
     $csv = array(array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '5555556778250000', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => '*****@*****.**', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'), array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '5555554530114002', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => '*****@*****.**', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'), array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => '*****@*****.**', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'), array('AMOUNT' => 100, 'OPERATIONTYPE' => 'payment', 'CARDCODE' => '5555556778250000', 'CARDVALIDITYDATE' => $this->tools->getFutureValidityDate(), 'CARDCVV' => '123', 'CARDFULLNAME' => 'John Doe', 'ORDERID' => 'order_' . time(), 'CLIENTIDENT' => 'john.doe', 'CLIENTEMAIL' => 'john.doe42', 'CLIENTEMAIL' => '*****@*****.**', 'DESCRIPTION' => 'Test', 'CLIENTUSERAGENT' => 'firefox', 'CLIENTIP' => '1.2.3.4', 'VERSION' => '2.0'));
     fputcsv($inputFile, array_keys(current($csv)), ';');
     foreach ($csv as $line) {
         fputcsv($inputFile, $line, ';');
     }
     rewind($inputFile);
     $batchApi = Be2bill_Api_ClientBuilder::buildSandboxBatchClient($this->getIdentifier(), $this->getPassword());
     $batchApi->setInputFile($inputFile);
     $batchApi->attach(new Be2bill_Api_Batch_Observer_Debug());
     $batchApi->attach(new Be2bill_Api_Batch_Observer_FileReport($outputFile));
     $batchApi->run();
     rewind($outputFile);
     $i = 0;
     while (!feof($outputFile)) {
         $line = fgetcsv($outputFile, null, ';');
         // HACK for phpunit version >= 5.2
         if ($line) {
             $i++;
         }
     }
     $this->expectOutputRegex('/Line 1.+\\nLine 2.+\\nLine 3.+\\nLine 4.+\\n/');
     $this->assertEquals(5, $i);
 }
Пример #22
0
 public function export(\Contao\DC_Table $dc)
 {
     $database = \Contao\Database::getInstance();
     $stage_id = $database->query("SELECT s.id FROM tl_beachcup_stage AS s WHERE s.start_date >= UNIX_TIMESTAMP() ORDER BY s.start_date ASC LIMIT 1")->fetchAssoc()["id"];
     $data = $database->query("select tl_beachcup_registration.id as ANMELDUNG_ID, tl_beachcup_tournament.name_de AS TURNIER, DATE_FORMAT(from_unixtime(tl_beachcup_registration.tstamp), '%d.%m.%Y') as DATUM_ANMELDUNG,\n                                    p1.surname as NACHNAME_1, p1.name as VORNAME_1, p1.tax_number as STEUER_NR_1, DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL p1.birth_date SECOND), '%d.%m.%Y') as GEB_DATUM_1, p1.birth_place as GEB_ORT_1, p1.gender as GESCHLECHT_1, p1.address as ADRESSE_1, p1.zip_code as PLZ_1, p1.city as ORT_1, p1.country as LAND_1, p1.email as EMAIL_1, p1.phone_number as TEL_1, p1.shirt_size as SHIRT_1, p1.has_shirt as SHIRT_ERHALTEN_1, p1.is_fipav as FIPAV_1, p1level.description_de as SPIELER_LEVEL_1, p1.has_medical_certificate as AERZTL_ZEUGNIS_1, p1.is_confirmed as EIGENERKLAERUNG_1,\n                                    p2.surname as NACHNAME_2, p2.name as VORNAME_2, p2.tax_number as STEUER_NR_2, DATE_FORMAT(DATE_ADD(FROM_UNIXTIME(0), INTERVAL p2.birth_date SECOND), '%d.%m.%Y') as GEB_DATUM_2, p2.birth_place as GEB_ORT_2, p2.gender as GESCHLECHT_2, p2.address as ADRESSE_2, p2.zip_code as PLZ_2, p2.city as ORT_2, p2.country as LAND_2, p2.email as EMAIL_2, p2.phone_number as TEL_2, p2.shirt_size as SHIRT_2, p2.has_shirt as SHIRT_ERHALTEN_2, p2.is_fipav as FIPAV_2, p2level.description_de as SPIELER_LEVEL_2, p2.has_medical_certificate as AERZTL_ZEUGNIS_2, p2.is_confirmed as EIGENERKLAERUNG_2,\n                                    tl_beachcup_registration_state.code as STATUS_ANMELDUNG\n                                    from tl_beachcup_registration\n                                    join tl_beachcup_team on tl_beachcup_team.id = tl_beachcup_registration.team_id\n                                    join tl_beachcup_player p1 on p1.id =  tl_beachcup_team.player_1\n                                    join tl_beachcup_player_level p1level on p1level.id = p1.player_level\n                                    join tl_beachcup_player p2 on p2.id =  tl_beachcup_team.player_2\n                                    join tl_beachcup_player_level p2level on p2level.id = p2.player_level\n                                    join tl_beachcup_tournament on tl_beachcup_tournament.id = tl_beachcup_registration.tournament_id\n                                    join tl_beachcup_registration_state on tl_beachcup_registration_state.id = tl_beachcup_registration.state_id\n                                    join tl_beachcup_stage on tl_beachcup_stage.id = tl_beachcup_tournament.stage_id\n                                    where tl_beachcup_stage.id = {$stage_id} and tl_beachcup_registration_state.code != 'REJECTED'\n                                    order by tl_beachcup_tournament.date, tl_beachcup_tournament.name_de, tl_beachcup_registration.tstamp;")->fetchAllAssoc();
     if (count($data) > 0) {
         $headers = array();
         foreach ($data[0] as $key => $value) {
             $headers[] = $key;
         }
         $file = fopen("php://memory", "w");
         fputcsv($file, $headers, ";");
         foreach ($data as $record) {
             fputcsv($file, $record, ";");
         }
         fseek($file, 0);
         header('Content-Encoding: iso-8859-1');
         header('Content-Type: application/csv; charset=iso-8859-1');
         header('Content-Disposition: attachement; filename="Anmeldungen.csv";');
         echo "";
         fpassthru($file);
         exit;
     }
     \Contao\Controller::redirect('contao/main.php?do=registration');
 }
 /**
  * @param resource $filePointer
  * @param array    $data
  * @param string   $separator
  * @param string   $enclosure
  * @return int
  */
 protected function writeCSVLine($filePointer, array $data, $separator = ',', $enclosure = '"')
 {
     if (true === is_resource($filePointer)) {
         return fputcsv($filePointer, $data, $separator, $enclosure);
     }
     return 0;
 }
 function execute($requests)
 {
     if (!LOG_C_ACCESS_LOG) {
         admin_client_redirect('top', '指定されたページにはアクセスできません');
     }
     $ktai_flag = $requests['ktai_flag'];
     $ymd = $requests['ymd'];
     $month_flag = $requests['month_flag'];
     $page_name = $requests['page_name'];
     $orderby = $requests['orderby'];
     header("Content-Type: application/octet-stream");
     header("Content-Disposition: attachment; filename=access_analysis_target_member.csv");
     $out = fopen('php://output', 'w');
     $csv_header = array('メンバーID', WORD_NICKNAME, 'アクセス数');
     for ($i = 0; $i < sizeof($csv_header); $i++) {
         $csv_header[$i] = mb_convert_encoding($csv_header[$i], 'SJIS', 'UTF-8');
     }
     fputcsv($out, $csv_header);
     $sum = 0;
     $page = 1;
     $page_size = -1;
     list($target_member) = p_access_analysis_target_member_access_member4ym_page_name($ymd, $month_flag, $page_name, $ktai_flag, $page, $page_size, $orderby);
     foreach ($target_member as $item) {
         $nickname = $item['is_c_member_exists'] ? $item['nickname'] : '(既に退会したメンバーです)';
         $nickname = mb_convert_encoding($nickname, 'SJIS', 'UTF-8');
         $csv_line = array($item['target_c_member_id'], $nickname, $item['count']);
         fputcsv($out, $csv_line);
         $sum += $item['count'];
     }
     fputcsv($out, array(mb_convert_encoding('合計', 'SJIS', 'UTF-8'), '', $sum));
     exit;
 }
Пример #25
0
function mc_format_csv($data)
{
    $keyed = false;
    // Create a stream opening it with read / write mode
    $stream = fopen('data://text/plain,' . "", 'w+');
    // Iterate over the data, writting each line to the text stream
    foreach ($data as $key => $val) {
        foreach ($val as $v) {
            $values = get_object_vars($v);
            if (!$keyed) {
                $keys = array_keys($values);
                fputcsv($stream, $keys);
                $keyed = true;
            }
            fputcsv($stream, $values);
        }
    }
    // Rewind the stream
    rewind($stream);
    // You can now echo it's content
    header("Content-type: text/csv");
    header("Content-Disposition: attachment; filename=my-calendar.csv");
    header("Pragma: no-cache");
    header("Expires: 0");
    echo stream_get_contents($stream);
    // Close the stream
    fclose($stream);
    die;
}
 function run()
 {
     $sql = "SELECT * FROM civicrm_metrics_server ORDER BY site_name, timestamp";
     $dao =& CRM_Core_DAO::executeQuery($sql);
     $rows = array();
     while ($dao->fetch()) {
         $row = array();
         $row['id'] = $dao->id;
         $row['site_name'] = $dao->site_name;
         $row['site_url'] = $dao->site_url;
         $row['timestamp'] = $dao->timestamp;
         $row['type'] = $dao->type;
         $row['data'] = $dao->data;
         $rows[] = $row;
     }
     if (array_key_exists("export", $_REQUEST) && $_REQUEST['export'] == 'csv') {
         header('Content-type: text/csv');
         header('Content-disposition: attachment;filename=metrics_data_' . date("Ymd_HiO") . '.csv');
         $output = fopen('php://output', 'w');
         $headers = array("Id", "Site Name", "Site URL", "Timestamp", "Metric Type", "Metric Data");
         fputcsv($output, $headers);
         foreach ($rows as $row) {
             fputcsv($output, $row);
         }
         fclose($output);
         die;
     } else {
         CRM_Utils_System::setTitle(ts('Metrics Report'));
         $this->assign('data', $rows);
         $this->assign('headers', array_keys($rows[0]));
         parent::run();
     }
 }
Пример #27
0
 public function generatesssAction()
 {
     header('Content-Type: text/csv; charset=utf-8');
     header('Content-Disposition: attachment; filename=codevalue' . rand() . '.csv');
     // create a file pointer connected to the output stream
     $output = fopen('php://output', 'w');
     #$rows = mysql_query("SELECT firstname,lastname,email,amount,bank_name,bank_accountnumber,bank_accountname FROM  tbl_withdraw_history as a JOIN tbl_accounts as b WHERE claim_status=0 AND a.accounts_id=b.accounts_id");
     // output the column headings
     fputcsv($output, array("Package Name", "Code Pin", "Code Value"));
     // loop over the rows, outputting them
     /*
     code_value
     code_pin
     code_package
     activated = 1
     code_referrer = 0;
     tbl_code
     */
     $loop = $_REQUEST['qty'];
     $x = explode("@@@", $_REQUEST['packages']);
     $code_package = $x[0];
     $code_name = $x[1];
     $start = 0;
     while ($start <= $loop) {
         $start++;
         $code_value = $this->RandomString();
         $code_pin = $this->RandomString();
         $query = "INSERT INTO tbl_code SET code_pin='{$code_pin}',code_package='{$code_package}',code_value='{$code_value}',activated='1'";
         mysql_query($query);
         fputcsv($output, array($code_name, $code_pin, $code_value));
     }
     exit;
 }
Пример #28
0
 public function main($argv)
 {
     $type = $argv[1];
     $year = $argv[2];
     $month = $argv[3];
     if (!$year or !$month or !in_array($type, array('town', 'village'))) {
         throw new Exception("Usage: php crawler.php <town or village> <year> <month>");
     }
     $fp = fopen(__DIR__ . "/outputs/{$type}/{$year}-{$month}.csv", "w");
     foreach ($this->getCountryList($year) as $county_id => $county_name) {
         $towns = $this->getTownsFromCountry($county_id, $year);
         if ('village' == $type) {
             foreach ($towns as $town_id => $town_name) {
                 $ret = $this->getDataFromTown($year, $month, $county_id, $county_name, $town_id, $town_name);
                 foreach ($ret as $village_name => $count) {
                     error_log($village_name);
                     fputcsv($fp, array($county_id, $county_name, $town_id, $town_name, $village_name, $count));
                 }
             }
         } else {
             $ret = $this->getDataFromCounty($year, $month, $county_id, $county_name);
             foreach ($ret as $town_name => $count) {
                 $town_id = array_search($town_name, $towns);
                 fputcsv($fp, array($county_id, $county_name, $town_id, $town_name, '總計', $count));
             }
         }
     }
     fclose($fp);
 }
Пример #29
0
 public function array_put_csv($filename, $assocDataArray)
 {
     $this->load->helper('csv');
     //        ob_clean();
     //        header('Pragma: public');
     //        header('Expires: 0');
     //        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
     //        header('Cache-Control: private', false);
     //        header('Content-Type: application/csv');
     //        header('Content-Disposition: attachment;filename=' . $fileName);
     //        $fp = fopen('php://output', 'w');
     //        foreach ($assocDataArray AS $values) {
     //            fputcsv($fp, $values);
     //        }
     //        fclose($fp);
     //        ob_flush();
     header("Content-Type: text/csv;charset=utf-8");
     header("Content-Disposition: attachment;filename=\"{$filename}\"");
     header("Pragma: no-cache");
     header("Expires: 0");
     $fp = fopen('php://output', 'w');
     foreach ($assocDataArray as $fields) {
         fputcsv($fp, $fields);
     }
     fclose($fp);
     exit;
 }
Пример #30
0
 public function testCreateCsv()
 {
     $testDb = new TestLiteDb();
     $testDb->createPlainTables(array('license_ref', 'license_map'));
     $dbManager = $testDb->getDbManager();
     $licenses = array();
     for ($i = 1; $i < 4; $i++) {
         $licenses[$i] = array('rf_pk' => $i, 'rf_shortname' => 'lic' . $i, 'rf_fullname' => 'lice' . $i, 'rf_text' => 'text' . $i, 'rf_url' => $i . $i, 'rf_notes' => 'note' . $i, 'rf_source' => 's' . $i, 'rf_detector_type' => 1, 'rf_risk' => $i - 1);
         $dbManager->insertTableRow('license_ref', $licenses[$i]);
     }
     $dbManager->insertTableRow('license_map', array('rf_fk' => 3, 'rf_parent' => 1, 'usage' => LicenseMap::CONCLUSION));
     $dbManager->insertTableRow('license_map', array('rf_fk' => 3, 'rf_parent' => 2, 'usage' => LicenseMap::REPORT));
     $licenseCsvExport = new LicenseCsvExport($dbManager);
     $head = array('shortname', 'fullname', 'text', 'parent_shortname', 'report_shortname', 'url', 'notes', 'source', 'risk');
     $out = fopen('php://output', 'w');
     $csv = $licenseCsvExport->createCsv();
     ob_start();
     fputcsv($out, $head);
     fputcsv($out, array($licenses[1]['rf_shortname'], $licenses[1]['rf_fullname'], $licenses[1]['rf_text'], null, null, $licenses[1]['rf_url'], $licenses[1]['rf_notes'], $licenses[1]['rf_source'], $licenses[1]['rf_risk']));
     fputcsv($out, array($licenses[2]['rf_shortname'], $licenses[2]['rf_fullname'], $licenses[2]['rf_text'], null, null, $licenses[2]['rf_url'], $licenses[2]['rf_notes'], $licenses[2]['rf_source'], $licenses[2]['rf_risk']));
     fputcsv($out, array($licenses[3]['rf_shortname'], $licenses[3]['rf_fullname'], $licenses[3]['rf_text'], $licenses[1]['rf_shortname'], $licenses[2]['rf_shortname'], $licenses[3]['rf_url'], $licenses[3]['rf_notes'], $licenses[3]['rf_source'], $licenses[3]['rf_risk']));
     $expected = ob_get_contents();
     ob_end_clean();
     assertThat($csv, is(equalTo($expected)));
     $delimiter = '|';
     $licenseCsvExport->setDelimiter($delimiter);
     $csv3 = $licenseCsvExport->createCsv(3);
     ob_start();
     fputcsv($out, $head, $delimiter);
     fputcsv($out, array($licenses[3]['rf_shortname'], $licenses[3]['rf_fullname'], $licenses[3]['rf_text'], $licenses[1]['rf_shortname'], $licenses[2]['rf_shortname'], $licenses[3]['rf_url'], $licenses[3]['rf_notes'], $licenses[3]['rf_source'], $licenses[3]['rf_risk']), $delimiter);
     $expected3 = ob_get_contents();
     ob_end_clean();
     assertThat($csv3, is(equalTo($expected3)));
 }