public function exportTable(DataContainer $dc)
 {
     $objConfig = $this->Database->prepare("SELECT * FROM tl_dataexchange_config WHERE id=?")->limit(1)->execute($this->Input->get('return') == '' ? $dc->id : $this->Input->get('id'));
     if ($objConfig->numRows < 1) {
         $this->redirect('contao/main.php?act=error');
     }
     $this->import('String');
     $this->loadDataContainer($objConfig->tableName);
     $objCSV = new CsvWriter();
     $arrData = array();
     $arrResult = $this->getFieldResults($objConfig);
     foreach ($arrResult as $arrRow) {
         $arrFieldData = array();
         foreach ($arrRow as $arrField) {
             if ($arrField['dcaField'] != '') {
                 $strValue = $this->formatValue($objConfig->tableName, $arrField['dcaField'], $arrField['value']);
             } else {
                 $strValue = $arrField['value'];
             }
             // Decode special entities (e.g. brackets), Contao automatically encodes them in the database
             $arrFieldData[] = $this->String->decodeEntities($strValue);
         }
         $arrData[] = $arrFieldData;
     }
     // Add header fields
     if ($objConfig->includeHeader) {
         $this->loadLanguageFile($objConfig->tableName);
         $arrHeader = array();
         foreach ($arrResult[0] as $id => $arrField) {
             if ($arrField['label'] != '') {
                 $arrHeader[] = $arrField['label'];
             } elseif ($arrField['dcaField'] != '') {
                 $arrHeader[] = $this->formatLabel($objConfig->tableName, $arrField['dcaField']);
             } else {
                 $arrHeader[] = $id;
             }
         }
         $objCSV->headerFields = $arrHeader;
     }
     $objCSV->seperator = $objConfig->exportCSVSeparator == "tab" ? "\t" : $objConfig->exportCSVSeparator;
     $objCSV->excel = $objConfig->exportCSVExcel;
     $objCSV->content = $arrData;
     if ($objConfig->exportToFile) {
         $strStoreDir = $objConfig->storeDir;
         if ($strStoreDir == '') {
             $strStoreDir = $GLOBALS['TL_CONFIG']['uploadPath'];
         }
         $objCSV->saveToFile(sprintf('%s/%s%s.csv', $strStoreDir, $this->replaceInsertTags($objConfig->prependString), $objConfig->tableName));
     } else {
         $objCSV->saveToBrowser();
     }
     if ($this->Input->get('return')) {
         $this->redirect('contao/main.php?do=' . $this->Input->get('return'));
     } else {
         $this->redirect('contao/main.php?do=dataexchange_config');
     }
 }
 function renderCsv()
 {
     $page = XmlDocumentHandler::getInstance();
     $page->setMimeType('text/csv');
     $page->setAttachmentName('export.csv');
     $writer = new CsvWriter();
     $writer->setData($this->data);
     return $writer->render();
 }
 public function testRender()
 {
     $list = array();
     $list[] = new CsvTestRow("hej där", 123456.999100091);
     $list[] = new CsvTestRow("kalle", 200.00000000001);
     $writer = new CsvWriter();
     $writer->setData($list);
     $expected_csv = '"col1";"col2"' . "\r\n" . '"hej där";"123456.99910009"' . "\r\n" . '"kalle";"200.00000000001"' . "\r\n";
     $this->assertEquals($writer->render(), $expected_csv);
 }
Exemple #4
0
 /**
  * initiate a SplFileObject::fputcsv method
  */
 protected static function initFputcsv()
 {
     if (is_null(self::$fputcsv)) {
         self::$fputcsv = new ReflectionMethod('\\SplFileObject', 'fputcsv');
         self::$fputcsv_param_count = self::$fputcsv->getNumberOfParameters();
     }
 }
 /**
  * {@inheritdoc}
  */
 public function getPath()
 {
     if (null === $this->resolvedFilePath) {
         $this->resolvedFilePath = parent::getPath();
         foreach ($this->context as $key => $value) {
             $this->resolvedFilePath = strtr($this->resolvedFilePath, ['%' . $key . '%' => $value]);
         }
     }
     return $this->resolvedFilePath;
 }
Exemple #6
0
 public function toCsv()
 {
     $writer = \CsvWriter::create();
     $data = $this->toArray();
     $writer->writeLine(array_keys($data));
     $writer->writeLine($data);
     $out = $writer->flush();
     $writer->close();
     return $out;
 }
 public function init(\SurveyObj $survey, $sLanguageCode, \FormattingOptions $oOptions)
 {
     parent::init($survey, $sLanguageCode, $oOptions);
     // Change filename
     $this->csvFilename = 'survey_' . $survey->id . '_R_data_file.csv';
     // Skip the first line with headers
     $this->doHeaders = true;
     $oOptions->answerFormat = "short";
     // force answer codes
     // Save fieldmap so we can use it in transformResponseValue
     $this->fieldmap = $survey->fieldMap;
 }
Exemple #8
0
 /**
  * CSV Index.
  *
  * @param string $type Model type. user for file name
  * 
  * @return void
  **/
 function admin_index($type = false)
 {
     if (false == $this->debug) {
         Configure::write('debug', 0);
     }
     if (!$type) {
         echo 'Model name missing';
         exit;
     }
     Configure::load('csver');
     if (is_null(Configure::read('Csver.whitelist'))) {
         echo 'Did you set up the config file? Need whitelist of allowed CSV models.';
         exit;
     }
     $this->type = $type;
     if ('*' != Configure::read('Csver.whitelist') && !in_array($type, Configure::read('Csver.whitelist'))) {
         echo 'Not permitted. Not on whitelist.';
         exit;
     }
     //We don't use Controller::loadModel() due to bug where if successful, doesn't return true.
     //If this fails, will just get a 404 error, so we don't bother any extra checking.
     $model = ClassRegistry::init($type);
     if (method_exists($model, 'csv')) {
         $data = $model->csv();
     } else {
         $data = $this->csv($model);
     }
     $filename = tempnam(TMP, '');
     App::import('Vendor', 'Csver.CsvWriter', array('file' => 'php-csv/csv.php'));
     $file = new CsvWriter($filename);
     //Add header row
     $file->addLine($data['header']);
     foreach ($data['results'] as $line) {
         $file->addLine($line[$type]);
     }
     $this->_output($filename);
 }
 /**
  * Returns the adapted heading using parent function
  *
  * @param Survey $survey
  * @param FormattingOptions $oOptions
  * @param string $fieldName
  * @return string (or false)
  */
 public function getFullHeading(SurveyObj $survey, FormattingOptions $oOptions, $fieldName)
 {
     $sQuestion = "";
     static $aColumnDone = array();
     switch ($this->oldHeadFormat) {
         case 'abbreviated':
             $sQuestion = parent::getAbbreviatedHeading($survey, $fieldName);
             break;
         case 'full':
             $sQuestion = parent::getFullHeading($survey, $oOptions, $fieldName);
             break;
         default:
         case 'code':
             if (isset($survey->fieldMap[$fieldName])) {
                 $sQuestion = viewHelper::getFieldCode($survey->fieldMap[$fieldName]);
             } else {
                 // Token field
                 $sQuestion = $column;
             }
             break;
     }
     if ($oOptions->headerSpacesToUnderscores) {
         $sQuestion = str_replace(' ', '_', $sQuestion);
     }
     if ($this->exportAnswerPosition == 'aseperatecodetext') {
         if (isset($survey->fieldMap[$fieldName])) {
             $aField = $survey->fieldMap[$fieldName];
             if (!self::sameTextAndCode($aField['type'], $fieldName)) {
                 if (!array_key_exists($fieldName, $aColumnDone)) {
                     // Code export
                     $sQuestion = $this->beforeHeadColumnCode . $sQuestion . $this->afterHeadColumnCode;
                     $aColumnDone[$fieldName] = 1;
                 } else {
                     // Text export
                     $sQuestion = $this->beforeHeadColumnFull . $sQuestion . $this->afterHeadColumnFull;
                     unset($aColumnDone[$fieldName]);
                 }
             } else {
                 $sQuestion = $sQuestion;
             }
         } else {
             $sQuestion = $sQuestion;
         }
     }
     return $sQuestion;
 }
 /**
  * Export tabular data to CSV-file
  * @param array $data
  * @param string $filename
  */
 public static function export_table_csv_utf8($data, $filename = 'export')
 {
     if (empty($data)) {
         return false;
     }
     $path = Chamilo::temp_file();
     $converter = new Utf8Encoder(null, true);
     $file = FileWriter::create($path, $converter);
     $file = CsvWriter::create($file);
     foreach ($data as $row) {
         $file->put($row);
     }
     $file->close();
     DocumentManager::file_send_for_download($path, false, $filename . '.csv');
     unlink($path);
     exit;
 }
 /**
  * 配列をCSV形式で書き出す
  * @param array $arr 書き込むCSVの配列
  * @access public
  * @see CsvWriter::write()
  */
 function write($arr)
 {
     static $b = false;
     if (!$b) {
         // 初回の書き込みの場合
         $b = true;
         $headers = array();
         foreach ($this->format as $key => $params) {
             $headers[] = $params['name'];
         }
         parent::write($headers);
     }
     $csv = array();
     foreach ($this->format as $key => $params) {
         $csv[$key] = $this->filter($arr[$key], $params);
     }
     parent::write($csv);
 }
 /**
  * Perform response transformation, for example F/M for female/male will be mapped to 1/2 values
  *
  * @param type $value
  * @param type $fieldType
  * @param FormattingOptions $oOptions
  * @return mixed
  */
 protected function transformResponseValue($value, $fieldType, FormattingOptions $oOptions)
 {
     parent::transformResponseValue($value, $fieldType, $oOptions);
     switch ($fieldType) {
         case 'G':
             // Gender question
             if ($value == 'F') {
                 return 1;
             } elseif ($value == 'M') {
                 return 2;
             }
             break;
         case 'C':
             // Yes/no/uncertain
             if ($value == 'Y') {
                 return 1;
             } elseif ($value == 'N') {
                 return 2;
             } elseif ($value == 'U') {
                 return 3;
             }
             break;
         case 'E':
             // Increase/same/decrease
             if ($value == 'I') {
                 return 1;
             } elseif ($value == 'S') {
                 return 2;
             } elseif ($value == 'D') {
                 return 3;
             }
             break;
         default:
             break;
     }
 }
Exemple #13
0
 public function generateCsv()
 {
     $companies = $this->db->getAll('SELECT DISTINCT * FROM `companies` ');
     echo "Получил компании \r\n";
     $companyCategories = $this->db->getAll('SELECT c.title, cc.category FROM `companies` c JOIN `company_categories` cc ON (cc.id = c.category_id)');
     echo "Получил категории компаний \r\n";
     $csvArr = [];
     $csvArr[] = ['Категория', 'Название компании', 'Ссылка на сайт', 'Основной телефон', 'Телефоны', 'Дополнительные контакты', 'Ссылка на страницу контактов', 'Город', 'Отзывы'];
     echo "Начало процесса формирования csv \r\n";
     foreach ($companies as $company) {
         echo $company['title'] . " \r\n";
         $company = $this->data($company);
         $categories = [];
         echo "Поиск категорий компании \r\n";
         foreach ($companyCategories as $key => $cc) {
             if ($company['title'] == html_entity_decode($cc['title'])) {
                 echo $cc['category'] . " \r\n";
                 $categories[] = $cc['category'];
                 unset($companyCategories[$key]);
             }
         }
         $categories = implode(', ', $categories);
         $phones = [];
         if ($company['phones'] && is_array($company['phones'])) {
             foreach ($company['phones'] as $phone) {
                 $phones[] = $phone['description'] . ' - ' . $phone['number'];
             }
         }
         $phones = implode(', ', $phones);
         $contacts = [];
         if ($company['other_contacts'] && is_array($company['other_contacts'])) {
             foreach ($company['other_contacts'] as $contact) {
                 $contacts[] = $contact['description'] . ' - ' . $contact['data'];
             }
         }
         $contacts = implode(', ', $contacts);
         $reviews = $company['reviews']['title'] . '; Ссылка на отзывы - ' . $company['reviews']['href'];
         $csvArr[] = [$categories, $company['title'], $company['site'], $company['main_phone'], $phones, $contacts, $company['contact_page'], $company['city'], $reviews];
     }
     echo "Запись csv файла \r\n";
     $file = date('d-m-Y') . '.csv';
     $path = CSV . $file;
     $csv = new CsvWriter($path, $csvArr);
     $csv->GetCsv();
     return $file;
 }
Exemple #14
0
 function testCsvReader_TwoLines()
 {
     $filename = dirname(__FILE__) . '/data/writer-one-line.csv';
     $csv = new CsvWriter($filename);
     $csv->addLine(array('One', 'Two words', 'One "quoted"', 'Single "quote'));
     $csv->addLine(array('Line Number', '"Two "" is here"', 'Is', 'It fine?'));
     $csv->close();
     $file = fopen(dirname(__FILE__) . '/data/writer-one-line.csv', 'r');
     $string1 = utf8_encode(fgets($file));
     $string2 = utf8_encode(fgets($file));
     fclose($file);
     @unlink($filename);
     $expected1 = 'One,Two words,"One ""quoted""","Single ""quote"' . "\r\n";
     $expected2 = 'Line Number,"""Two """" is here""",Is,It fine?' . "\r\n";
     $this->assertEqual($string1, $expected1);
     $this->assertEqual($string2, $expected2);
 }
 protected function writer_headers()
 {
     if ($this->headers_written) {
         return;
     }
     $this->headers_written = true;
     $map = $this->map;
     if (!is_array($map)) {
         return;
     }
     $headers = array();
     foreach ($map as $key => $value) {
         $headers[] = $value;
     }
     parent::put($headers);
 }
if (empty($options)) {
    // fallback
    $options["language"] = "de";
}
$skippedProducts = 0;
$mapper = new LanguageMapper($options["language"]);
$feedFilename = sprintf("%s/Mey_%s_%s.csv", "/opt/productexport", $mapper->getLabel(), date("Y-m-d_H-m-s"));
$start = microtime(true);
$data = [];
$brokenProducts = [];
$gc = gc_enabled();
Mage::app()->setCurrentStore(Mage::getModel('core/store')->load($mapper->getStoreId()));
$taxCalc = new TaxCalculation(Mage);
$open = count($products);
$dataWritten = false;
$writer = new CsvWriter($feedFilename);
$productIds = Mage::getModel('catalog/product')->getCollection()->addAttributeToFilter('type_id', array('eq' => 'configurable'))->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))->getAllIds();
$open = count($productIds);
foreach ($productIds as $id) {
    $product = Mage::getModel('catalog/product')->load($id);
    $websites = $product->getWebsiteIds();
    if (!inMainStore($websites)) {
        $websites = implode(",", $websites);
        echo "[wrong website] skip {$id}, websites: {$websites}\n";
        $skippedProducts++;
        continue;
    }
    $data = [];
    $categoryData = [];
    $configProduct = new ConfigurableProduct($product);
    $categories = $configProduct->getCategoryIds();
 public function export_csv()
 {
     $c_id = Request::get_c_id();
     $session_id = Request::get_session_id();
     $root = (object) array();
     $root->c_id = $c_id;
     $root->id = 0;
     $root->session_id = $session_id;
     $links = LinkRepository::instance()->find_by_category($root);
     $repo = LinkCategory::repository();
     $categories = $repo->find_by_course($c_id, $session_id);
     $temp = Chamilo::temp_file();
     $writer = \CsvWriter::create(new \FileWriter($temp));
     $headers = array();
     $headers[] = 'url';
     $headers[] = 'title';
     $headers[] = 'description';
     $headers[] = 'target';
     $headers[] = 'category_title';
     $headers[] = 'category_description';
     $writer->put($headers);
     foreach ($links as $link) {
         $data = array();
         $data[] = $link->url;
         $data[] = $link->title;
         $data[] = $link->description;
         $data[] = $link->target;
         $data[] = '';
         $data[] = '';
         $writer->put($data);
     }
     foreach ($categories as $category) {
         foreach ($category->links as $link) {
             $data = array();
             $data[] = $link->url;
             $data[] = $link->title;
             $data[] = $link->description;
             $data[] = $link->target;
             $data[] = $category->category_title;
             $data[] = $category->description;
             $writer->put($data);
         }
     }
     \DocumentManager::file_send_for_download($temp, true, get_lang('Links') . '.csv');
 }
 /**
  * Root function for any export results action
  *
  * @param mixed $iSurveyId
  * @param mixed $sLanguageCode
  * @param csv|doc|pdf|xls $sExportPlugin Type of export
  * @param FormattingOptions $oOptions
  * @param string $sFilter 
  */
 function exportSurvey($iSurveyId, $sLanguageCode, $sExportPlugin, FormattingOptions $oOptions, $sFilter = '')
 {
     //Do some input validation.
     if (empty($iSurveyId)) {
         safeDie('A survey ID must be supplied.');
     }
     if (empty($sLanguageCode)) {
         safeDie('A language code must be supplied.');
     }
     if (empty($oOptions)) {
         safeDie('Formatting options must be supplied.');
     }
     if (empty($oOptions->selectedColumns)) {
         safeDie('At least one column must be selected for export.');
     }
     //echo $oOptions->toString().PHP_EOL;
     $writer = null;
     $iSurveyId = sanitize_int($iSurveyId);
     if ($oOptions->output == 'display') {
         header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
         header("Pragma: public");
     }
     switch ($sExportPlugin) {
         case "doc":
             $writer = new DocWriter();
             break;
         case "xls":
             $writer = new ExcelWriter();
             break;
         case "pdf":
             $writer = new PdfWriter();
             break;
         case "csv":
         default:
             $writer = new CsvWriter();
             break;
     }
     $surveyDao = new SurveyDao();
     $survey = $surveyDao->loadSurveyById($iSurveyId);
     $writer->init($survey, $sLanguageCode, $oOptions);
     $iBatchSize = 100;
     $iCurrentRecord = $oOptions->responseMinRecord - 1;
     $bMoreRecords = true;
     $first = true;
     while ($bMoreRecords) {
         $iExported = $surveyDao->loadSurveyResults($survey, $iBatchSize, $iCurrentRecord, $oOptions->responseMaxRecord, $sFilter);
         $iCurrentRecord += $iExported;
         $writer->write($survey, $sLanguageCode, $oOptions, $first);
         $first = false;
         $bMoreRecords = $iExported == $iBatchSize;
     }
     $result = $writer->close();
     if ($oOptions->output == 'file') {
         return $writer->filename;
     } else {
         return $result;
     }
 }
 /**
  * Set header line
  *
  * @param   string[] headers
  * @throws  lang.IllegalStateException if writing has already started
  */
 public function setHeaders($headers)
 {
     parent::setHeaders($headers);
     $this->keys = $headers;
 }
Exemple #20
0
<?php

require_once '../csv.php';
$data = array(array('cell one', 'cell two', 'cell three'), array('cell four', 'cell five', 'cell six'), array('cell seven', 'cell eight', 'cell nine'));
// make sure your web server has permission to write to the folder
$file = new CsvWriter(dirname(__FILE__) . '/../tests/data/file.csv');
foreach ($data as $line) {
    $file->addLine($line);
}