public function testHugeNumberOfColumns() { $obj = new CSV(); $data = $obj->with(__DIR__ . '/read_hugenumberofcolumns.csv')->toArray(); $arr = array(array_fill(0, 2000, 'row')); $this->assertEquals($data, $arr); }
public function testCustomDelimiter() { $csv = new CSV($this->rows, $this->headers, '|'); $output = $csv->render(); $expected = "name|age\nandrew|25\nbob|37\n"; $this->assertEquals($expected, $output); }
/** * @name exportOperation($pParam) * @desc Donne les opérations sur le compte du zeybu */ public function exportOperation($pParam) { $lVr = CompteAssociationValid::validRecherche($pParam); if ($lVr->getValid()) { $lDateDebut = NULL; if (!empty($pParam['dateDebut'])) { $lDateDebut = $pParam['dateDebut']; } $lDateFin = NULL; if (!empty($pParam['dateFin'])) { $lDateFin = $pParam['dateFin']; } $lCSV = new CSV(); $lCSV->setNom('CompteAssociation.csv'); // Le Nom // L'entete $lEntete = array("Date", "Compte", "Libelle", "Paiement", "N°", "Debit", "", "Credit", ""); $lCSV->setEntete($lEntete); // Les données $lOperationService = new OperationService(); $lOperations = $lOperationService->rechercheOperationAssociation($lDateDebut, $lDateFin); $lContenuTableau = array(); foreach ($lOperations as $lOperation) { $lDate = StringUtils::extractDate($lOperation->getOpeDate()); $lPaiement = ''; if (!is_null($lOperation->getTppType())) { $lPaiement = $lOperation->getTppType(); } $lCheque = ''; if (!is_null($lOperation->getNumeroCheque())) { $lCheque = $lOperation->getNumeroCheque(); } $lDebit = ''; $lCredit = ''; if ($lOperation->getOpeMontant() < 0) { $lDebit = $lOperation->getOpeMontant() * -1; } else { $lCredit = $lOperation->getOpeMontant(); } $lLignecontenu = array($lDate, $lOperation->getCptLabel(), $lOperation->getOpeLibelle(), $lPaiement, $lCheque, $lDebit, SIGLE_MONETAIRE, $lCredit, SIGLE_MONETAIRE); array_push($lContenuTableau, $lLignecontenu); } $lCSV->setData($lContenuTableau); // Export en CSV $lCSV->output(); } else { return $lVr; } }
/** * @name getListePaiementExport($pParam) * @return InfoMarcheVR * @desc Retourne la liste des adhérents qui ont réservé sur cette commande et les infos sur la commande. */ public function getListePaiementExport($pParam) { $lVr = MarcheValid::validGetMarche($pParam); if ($lVr->getValid()) { $lIdMarche = $pParam["id"]; $lTypePaiement = $pParam["type"]; $lCSV = new CSV(); $lCSV->setNom('Caisse.csv'); // Le Nom // L'entete $lEntete = array("Date", "N°", "Compte", "Nom", "Prénom", "Montant", ""); $lOperationService = new OperationService(); if ($lTypePaiement == 1) { $lOperations = $lOperationService->getListeEspeceCaisse($lIdMarche); } else { array_push($lEntete, "N°"); $lOperations = $lOperationService->getListeChequeCaisse($lIdMarche); } $lCSV->setEntete($lEntete); // Les données $lContenuTableau = array(); foreach ($lOperations as $lOperation) { if (!is_null($lOperation->getCptLabel())) { $lDate = StringUtils::extractDate($lOperation->getOpeDate()); if (is_null($lOperation->getAdhNumero())) { $lAdhNumero = ''; $lAdhNom = ''; $lAdhPrenom = ''; } else { $lAdhNumero = $lOperation->getAdhNumero(); $lAdhNom = $lOperation->getAdhNom(); $lAdhPrenom = $lOperation->getAdhPrenom(); } $lLignecontenu = array($lDate, $lAdhNumero, $lOperation->getCptLabel(), $lAdhNom, $lAdhPrenom, $lOperation->getOpeMontant(), SIGLE_MONETAIRE); if ($lTypePaiement == 2) { $lChampComplementaire = $lOperation->getOpeTypePaiementChampComplementaire(); array_push($lLignecontenu, $lChampComplementaire[3]->getValeur()); } array_push($lContenuTableau, $lLignecontenu); } } $lCSV->setData($lContenuTableau); // Export en CSV $lCSV->output(); } else { return $lVr; } }
function OnLoadPageData() { # Require an API key to include personal contact details to avoid spam bots picking them up $api_keys = $this->GetSettings()->GetApiKeys(); $valid_key = false; if (isset($_GET['key']) and in_array($_GET['key'], $api_keys)) { $valid_key = true; } $data = array(); $data[] = array("Match id", "Title", "Start time", "Latitude", "Longitude", "Website", "Description"); require_once 'stoolball/match-manager.class.php'; require_once "search/match-search-adapter.class.php"; $match_manager = new MatchManager($this->GetSettings(), $this->GetDataConnection()); $match_manager->FilterByDateStart(gmdate("U")); $match_manager->ReadByMatchId(); while ($match_manager->MoveNext()) { $match = $match_manager->GetItem(); $adapter = new MatchSearchAdapter($match); /* @var $match Match */ # Add this match to the data array $data[] = array($match->GetId(), $match->GetTitle(), $match->GetStartTime(), $match->GetGround() instanceof Ground ? $match->GetGround()->GetAddress()->GetLatitude() : "", $match->GetGround() instanceof Ground ? $match->GetGround()->GetAddress()->GetLongitude() : "", "https://" . $this->GetSettings()->GetDomain() . $match->GetNavigateUrl(), $adapter->GetSearchDescription()); } unset($match_manager); require_once "data/csv.class.php"; CSV::PublishData($data); # Test code only. Comment out CSV publish line above to enable display as a table. require_once "xhtml/tables/xhtml-table.class.php"; $table = new XhtmlTable(); $table->BindArray($data, false, false); echo $table; }
public function generate() { $reportManager = new ReportManager(Input::all()); $report = $reportManager->generate(); $dateTime = new DateTime('NOw'); return CSV::fromArray($report)->setHeaderRowExists(false)->render('Reporte_' . Input::get('report', '') . '_' . $dateTime->getTimestamp() . '.csv'); }
static function read() { $items = array(); while (($data = CSV::read_line()) !== FALSE) { $items[] = $data; } return $items; }
public function testPutCreatesFile() { $obj = new CSV(); $arr = array(array('name' => 'name1', 'address' => 'address1'), array('name' => 'name2', 'address' => 'address2')); $obj->with($arr)->put('tests' . DIRECTORY_SEPARATOR . 'putTest.csv'); $this->assertFileExists('tests' . DIRECTORY_SEPARATOR . 'putTest.csv'); unlink('tests' . DIRECTORY_SEPARATOR . 'putTest.csv'); }
function saveToCSV($extend_to_resources = true, $filename = null) { if (!$filename) { $csv = new CSV("csv/datasets-" . date("YmdHis") . "-" . max(0, $extend_to_resources) . ".csv"); } else { $csv = new CSV($filename); } if ($extend_to_resources) { $csv->addArrayHeader(array("Thema", "Categorie", "Naam", "Titel", "Beschrijving", "Tags", "Eigenaar", "Eigenaar e-mail", "Contactpersoon", "Contact e-mail", "Webadres", "Vrijgegeven", "Aangepast", "Tijd vanaf", "Tijd tot", "Tijd detailniveau", "Updatefrequentie", "Licentie", "Dataset url", "Dataset beschrijving", "Bestandsformaat")); } else { $csv->addArrayHeader(array("Thema", "Categorie", "Naam", "Titel", "Beschrijving", "Tags", "Eigenaar", "Eigenaar e-mail", "Contactpersoon", "Contact e-mail", "Webadres", "Vrijgegeven", "Aangepast", "Tijd vanaf", "Tijd tot", "Tijd detailniveau", "Updatefrequentie", "Licentie", "Directe url", "Aantal datasets", "Datasets")); } foreach ($this->datasets as $name => $dataset) { if ($extend_to_resources) { foreach ($dataset->res_description as $key => $description) { $thema = $this->themas[$dataset->groups[0]]; $categorie = $this->categorien[$dataset->groups[0]]; $item = array($thema, $categorie, $dataset->name, $dataset->title, $dataset->notes, implode(" ", $dataset->tags), $dataset->author, $dataset->author_email, $dataset->extras->contact_name, $dataset->extras->contact_email, $dataset->extras->website, $dataset->extras->publication_date, $dataset->metadata_modified, $dataset->extras->time_period_from, $dataset->extras->time_period_to, $dataset->extras->time_period_detail_level, $dataset->extras->update_frequency, $dataset->license_id, $dataset->res_url[$key], $description, $dataset->res_format[$key]); $csv->addArray($item); } } else { //Only datasets $thema = $this->themas[$dataset->groups[0]]; $categorie = $this->categorien[$dataset->groups[0]]; $url = DATA_URL . "?dataset=" . $dataset->name; $count = 0; $sets = ""; $splitter = ""; foreach ($dataset->res_description as $key => $description) { $count++; $sets .= $splitter . $description; $splitter = ", "; } $item = array($thema, $categorie, $dataset->name, $dataset->title, $dataset->notes, implode(" ", $dataset->tags), $dataset->author, $dataset->author_email, $dataset->extras->contact_name, $dataset->extras->contact_email, $dataset->extras->website, $dataset->extras->publication_date, $dataset->metadata_modified, $dataset->extras->time_period_from, $dataset->extras->time_period_to, $dataset->extras->time_period_detail_level, $dataset->extras->update_frequency, $dataset->license_id, $url, $count, $sets); $csv->addArray($item); } } $csv->write(); }
function OnLoadPageData() { # Require an API key to include personal contact details to avoid spam bots picking them up $api_keys = $this->GetSettings()->GetApiKeys(); $valid_key = false; if (isset($_GET['key']) and in_array($_GET['key'], $api_keys)) { $valid_key = true; } $data = array(); $data[] = array("Club/ facility name", "Address 1", "Address 2", "Address 3", "Address 4", "Address 5", "City", "Postcode", "Country", "Tel", "Email", "Website", "Activities", "Opening times"); require_once 'stoolball/team-manager.class.php'; $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection()); $team_manager->FilterByActive(true); $team_manager->FilterByTeamType(array(Team::REGULAR)); $team_manager->ReadById(); while ($team_manager->MoveNext()) { /* @var $team Team */ $team = $team_manager->GetItem(); # NHS choices can only import records with a postcode if (!$team->GetGround()->GetAddress()->GetPostcode()) { continue; } $address = array(); if ($team->GetGround()->GetAddress()->GetSaon()) { $address[] = $team->GetGround()->GetAddress()->GetSaon(); } if ($team->GetGround()->GetAddress()->GetPaon()) { $address[] = $team->GetGround()->GetAddress()->GetPaon(); } if ($team->GetGround()->GetAddress()->GetStreetDescriptor()) { $address[] = $team->GetGround()->GetAddress()->GetStreetDescriptor(); } if ($team->GetGround()->GetAddress()->GetLocality()) { $address[] = $team->GetGround()->GetAddress()->GetLocality(); } if ($team->GetGround()->GetAddress()->GetAdministrativeArea()) { $address[] = $team->GetGround()->GetAddress()->GetAdministrativeArea(); } $data[] = array($team->GetName() . " Stoolball Club", isset($address[0]) ? $address[0] : "", isset($address[1]) ? $address[1] : "", isset($address[2]) ? $address[2] : "", isset($address[3]) ? $address[3] : "", isset($address[4]) ? $address[4] : "", $team->GetGround()->GetAddress()->GetTown(), $team->GetGround()->GetAddress()->GetPostcode(), "England", $valid_key ? $team->GetContactPhone() : "", $valid_key ? $team->GetContactEmail() : "", $team->GetWebsiteUrl() ? $team->GetWebsiteUrl() : "https://" . $this->GetSettings()->GetDomain() . $team->GetNavigateUrl(), "stoolball", preg_replace('/\\[[^]]+\\]/', "", $team->GetPlayingTimes())); } unset($team_manager); require_once "data/csv.class.php"; CSV::PublishData($data); # Test code only. Comment out CSV publish line above to enable display as a table. require_once "xhtml/tables/xhtml-table.class.php"; $table = new XhtmlTable(); $table->BindArray($data, false, false); echo $table; }
/** * This function responses to * the get request of /admin/member * and show all member as list */ public function getViewAllMember($msg = null) { if (!empty($msg) && $msg == 1) { return View::make('adminArea.member.view')->with('members', Member::orderBy('id', 'desc')->get())->with('success', 'Member has been deleted successfully'); } if (!empty($msg) && $msg == 'csv-for-mailchimp') { $members = Member::select('first_name', 'last_name', 'email')->get()->toArray(); return CSV::fromArray($members)->render('Members CSV for MailChimp.csv'); } if (!empty($msg) && $msg == 'csv-for-sms-sender') { $members = Member::select('mobile_no')->get()->toArray(); return CSV::fromArray($members)->render('Members CSV for SMS Sender.csv'); } return View::make('adminArea.member.view')->with('members', Member::orderBy('id', 'desc')->get()); }
function OnLoadPageData() { # Require an API key to include personal contact details to avoid spam bots picking them up $api_keys = $this->GetSettings()->GetApiKeys(); $valid_key = false; if (isset($_GET['key']) and in_array($_GET['key'], $api_keys)) { $valid_key = true; } $data = array(); $data[] = array("Team id", "Team name", "Player type", "Home ground name", "Street name", "Locality", "Town", "Administrative area", "Postcode", "Country", "Latitude", "Longitude", "Contact phone", "Contact email", "Website", "Description"); require_once 'stoolball/team-manager.class.php'; $team_manager = new TeamManager($this->GetSettings(), $this->GetDataConnection()); $team_manager->FilterByActive(true); $team_manager->FilterByTeamType(array(Team::REGULAR)); $team_manager->ReadById(); while ($team_manager->MoveNext()) { $team = $team_manager->GetItem(); /* @var $team Team */ # Spogo can only import records with contact details if (!$team->GetContactPhone() and !$team->GetContactEmail()) { continue; } # Combine free text fields into a description field $description = $team->GetIntro(); if ($description) { $description .= "\n\n"; } if ($team->GetPlayingTimes()) { $description .= $team->GetPlayingTimes() . "\n\n"; } if ($team->GetCost()) { $description .= $team->GetCost(); } # Add this team to the data array $data[] = array($team->GetId(), $team->GetName() . " Stoolball Club", PlayerType::Text($team->GetPlayerType()), $team->GetGround()->GetAddress()->GetPaon(), $team->GetGround()->GetAddress()->GetStreetDescriptor(), $team->GetGround()->GetAddress()->GetLocality(), $team->GetGround()->GetAddress()->GetTown(), $team->GetGround()->GetAddress()->GetAdministrativeArea(), $team->GetGround()->GetAddress()->GetPostcode(), "England", $team->GetGround()->GetAddress()->GetLatitude(), $team->GetGround()->GetAddress()->GetLongitude(), $valid_key ? $team->GetContactPhone() : "", $valid_key ? $team->GetContactEmail() : "", $team->GetWebsiteUrl() ? $team->GetWebsiteUrl() : "https://" . $this->GetSettings()->GetDomain() . $team->GetNavigateUrl(), trim(html_entity_decode(strip_tags($description), ENT_QUOTES))); } unset($team_manager); require_once "data/csv.class.php"; CSV::PublishData($data); # Test code only. Comment out CSV publish line above to enable display as a table. require_once "xhtml/tables/xhtml-table.class.php"; $table = new XhtmlTable(); $table->BindArray($data, false, false); echo $table; }
/** This functions loads the data related to each page or layout for a page we load all files in the related directory for a layout we check the "datas-sources" attribute of our layout_file.json and load them In your real world application you can load data only when it is needed according to each page inside controllers */ private function load_data($data_dir) { $data_files = array(); $format = "/([0-9a-z\\-_]+)\\.(json|csv)\$/i"; //see if there's a folder for partial data relating to this page or layout //if so iterate all json/csv files and load the data $partial_data_folder = "{$data_dir}/{$this->type}s/partials/{$this->name}"; $stats = null; if (is_dir($partial_data_folder)) { $files = scandir($partial_data_folder); foreach ($files as $name) { if ($name == '.' or $name == '..') { continue; } if (!preg_match($format, $name, $filename)) { continue; } $data_files[$filename[1]] = "{$partial_data_folder}/{$name}"; } } foreach ($data_files as $var_name => $var_value) { $new_data = ''; if (preg_match("/\\.json\$/i", $data_files[$var_name])) { $new_data = json_decode(file_get_contents($data_files[$var_name]), TRUE); } else { if (preg_match("/\\.csv\$/i", $data_files[$var_name])) { //load csv data into an array $new_data = CSV::to_array($data_files[$var_name]); foreach ($new_data as &$data) { if (isset($data['status'])) { $data[$data['status']] = true; } } } } $this->vars[str_replace('.', '_', $var_name)] = $new_data; //here we replace '.' with '_' in variable names, so template compiler can recognize it as a variable not an object //for example change sidebar.navList to sidebar_navList , because sidebar is not an object } return true; }
$result[0] = $r['rows']; $r = $c->clasificacionFinal($rondas, $mangas, 3); $result[3] = $r['rows']; } else { $r = $c->clasificacionFinal($rondas, $mangas, 6); $result[6] = $r['rows']; $r = $c->clasificacionFinal($rondas, $mangas, 7); $result[7] = $r['rows']; } break; case 2: // recorrido conjunto large+medium+small if ($heights == 3) { $r = $c->clasificacionFinal($rondas, $mangas, 4); $result[4] = $r['rows']; } else { $r = $c->clasificacionFinal($rondas, $mangas, 8); $result[8] = $r['rows']; } break; } $first = true; foreach ($result as $res) { $csv = new CSV($prueba, $jornada, $mangas, $res); echo $csv->composeTable($first); $first = false; } } catch (Exception $e) { do_log($e->getMessage()); die($e->getMessage()); }
public function convert($filename, $format = self::STANDARD) { if ($this->mode != self::READ) { return; } if ($format == self::AUTO) { $format = self::STANDARD; } $csv = CSV::create($filename, CSV::EXCEL); $this->each(function ($row) use($csv) { $csv->write($row); }); return $csv; }
<?php class CSV { //private $_csv_file = null; public $_csv_file = null; public function __construct($csv_file) { if (file_exists($csv_file)) { $this->_csv_file = $csv_file; } else { throw new Exception("Файл \"{$csv_file}\" не найден"); } } public function getCSV() { $handle = fopen($this->_csv_file, "r"); $array_line_full = array(); while (($line = fgetcsv($handle, 0, ";")) !== FALSE) { $array_line_full[] = $line; } fclose($handle); return $array_line_full; } } /// $csv = new CSV("file.csv"); $get_csv = $csv->getCSV(); foreach ($get_csv as $value) { echo $value[5]; }
<script type="text/javascript" language="javascript"> </script> </head> <body> <h1>TCAT :: Export URLs</h1> <?php validate_all_variables(); $filename = get_filename_for_export('urlsExport'); $csv = new CSV($filename, $outputformat); $csv->writeheader(array('tweet_id', 'url', 'url_expanded', 'url_followed')); $sql = "SELECT t.id as id, u.url as url, u.url_expanded as url_expanded, u.url_followed as url_followed FROM " . $esc['mysql']['dataset'] . "_tweets t, " . $esc['mysql']['dataset'] . "_urls u "; $sql .= sqlSubset(); $sql .= " AND u.tweet_id = t.id ORDER BY id"; $sqlresults = mysql_unbuffered_query($sql); $out = ""; if ($sqlresults) { while ($data = mysql_fetch_assoc($sqlresults)) { $csv->newrow(); $csv->addfield($data['id'], 'integer'); $csv->addfield($data['url'], 'string'); if (isset($data['url_followed']) && strlen($data['url_followed']) > 1) { $csv->addfield($data['url'], 'string'); } else { $csv->addfield('', 'string');
public function execute(array &$param_pool = null) { $result = new XMLElement($this->dsParamROOTELEMENT); // When DS is called out of the Frontend context, this will enable // {$root} and {$workspace} parameters to be evaluated if (empty($this->_env)) { $this->_env['env']['pool'] = array('root' => URL, 'workspace' => WORKSPACE); } try { require_once TOOLKIT . '/class.gateway.php'; require_once TOOLKIT . '/class.xsltprocess.php'; require_once CORE . '/class.cacheable.php'; $this->dsParamURL = $this->parseParamURL($this->dsParamURL); if (isset($this->dsParamXPATH)) { $this->dsParamXPATH = $this->__processParametersInString(stripslashes($this->dsParamXPATH), $this->_env); } // Builds a Default Stylesheet to transform the resulting XML with $stylesheet = new XMLElement('xsl:stylesheet'); $stylesheet->setAttributeArray(array('version' => '1.0', 'xmlns:xsl' => 'http://www.w3.org/1999/XSL/Transform')); $output = new XMLElement('xsl:output'); $output->setAttributeArray(array('method' => 'xml', 'version' => '1.0', 'encoding' => 'utf-8', 'indent' => 'yes', 'omit-xml-declaration' => 'yes')); $stylesheet->appendChild($output); $template = new XMLElement('xsl:template'); $template->setAttribute('match', '/'); $instruction = new XMLElement('xsl:copy-of'); // Namespaces if (isset($this->dsParamNAMESPACES) && is_array($this->dsParamNAMESPACES)) { foreach ($this->dsParamNAMESPACES as $name => $uri) { $instruction->setAttribute('xmlns' . ($name ? ":{$name}" : null), $uri); } } // XPath $instruction->setAttribute('select', $this->dsParamXPATH); $template->appendChild($instruction); $stylesheet->appendChild($template); $stylesheet->setIncludeHeader(true); $xsl = $stylesheet->generate(true); // Check for an existing Cache for this Datasource $cache_id = self::buildCacheID($this); $cache = Symphony::ExtensionManager()->getCacheProvider('remotedatasource'); $cachedData = $cache->check($cache_id); $writeToCache = null; $isCacheValid = true; $creation = DateTimeObj::get('c'); // Execute if the cache doesn't exist, or if it is old. if (!is_array($cachedData) || empty($cachedData) || time() - $cachedData['creation'] > $this->dsParamCACHE * 60) { if (Mutex::acquire($cache_id, $this->dsParamTIMEOUT, TMP)) { $ch = new Gateway(); $ch->init($this->dsParamURL); $ch->setopt('TIMEOUT', $this->dsParamTIMEOUT); // Set the approtiate Accept: headers depending on the format of the URL. if ($this->dsParamFORMAT == 'xml') { $ch->setopt('HTTPHEADER', array('Accept: text/xml, */*')); } elseif ($this->dsParamFORMAT == 'json') { $ch->setopt('HTTPHEADER', array('Accept: application/json, */*')); } elseif ($this->dsParamFORMAT == 'csv') { $ch->setopt('HTTPHEADER', array('Accept: text/csv, */*')); } self::prepareGateway($ch); $data = $ch->exec(); $info = $ch->getInfoLast(); Mutex::release($cache_id, TMP); $data = trim($data); $writeToCache = true; // Handle any response that is not a 200, or the content type does not include XML, JSON, plain or text if ((int) $info['http_code'] != 200 || !preg_match('/(xml|json|csv|plain|text)/i', $info['content_type'])) { $writeToCache = false; $result->setAttribute('valid', 'false'); // 28 is CURLE_OPERATION_TIMEOUTED if ($info['curl_error'] == 28) { $result->appendChild(new XMLElement('error', sprintf('Request timed out. %d second limit reached.', $timeout))); } else { $result->appendChild(new XMLElement('error', sprintf('Status code %d was returned. Content-type: %s', $info['http_code'], $info['content_type']))); } return $result; } else { if (strlen($data) > 0) { // Handle where there is `$data` // If it's JSON, convert it to XML if ($this->dsParamFORMAT == 'json') { try { require_once TOOLKIT . '/class.json.php'; $data = JSON::convertToXML($data); } catch (Exception $ex) { $writeToCache = false; $errors = array(array('message' => $ex->getMessage())); } } elseif ($this->dsParamFORMAT == 'csv') { try { require_once EXTENSIONS . '/remote_datasource/lib/class.csv.php'; $data = CSV::convertToXML($data); } catch (Exception $ex) { $writeToCache = false; $errors = array(array('message' => $ex->getMessage())); } } elseif ($this->dsParamFORMAT == 'txt') { $txtElement = new XMLElement('entry'); $txtElement->setValue(General::wrapInCDATA($data)); $data = $txtElement->generate(); $txtElement = null; } else { if (!General::validateXML($data, $errors, false, new XsltProcess())) { // If the XML doesn't validate.. $writeToCache = false; } } // If the `$data` is invalid, return a result explaining why if ($writeToCache === false) { $error = new XMLElement('errors'); $error->setAttribute('valid', 'false'); $error->appendChild(new XMLElement('error', __('Data returned is invalid.'))); foreach ($errors as $e) { if (strlen(trim($e['message'])) == 0) { continue; } $error->appendChild(new XMLElement('item', General::sanitize($e['message']))); } $result->appendChild($error); return $result; } } elseif (strlen($data) == 0) { // If `$data` is empty, set the `force_empty_result` to true. $this->_force_empty_result = true; } } } else { // Failed to acquire a lock $result->appendChild(new XMLElement('error', __('The %s class failed to acquire a lock.', array('<code>Mutex</code>')))); } } else { // The cache is good, use it! $data = trim($cachedData['data']); $creation = DateTimeObj::get('c', $cachedData['creation']); } // Visit the data $this->exposeData($data); // If `$writeToCache` is set to false, invalidate the old cache if it existed. if (is_array($cachedData) && !empty($cachedData) && $writeToCache === false) { $data = trim($cachedData['data']); $isCacheValid = false; $creation = DateTimeObj::get('c', $cachedData['creation']); if (empty($data)) { $this->_force_empty_result = true; } } // If `force_empty_result` is false and `$result` is an instance of // XMLElement, build the `$result`. if (!$this->_force_empty_result && is_object($result)) { $proc = new XsltProcess(); $ret = $proc->process($data, $xsl); if ($proc->isErrors()) { $result->setAttribute('valid', 'false'); $error = new XMLElement('error', __('Transformed XML is invalid.')); $result->appendChild($error); $errors = new XMLElement('errors'); foreach ($proc->getError() as $e) { if (strlen(trim($e['message'])) == 0) { continue; } $errors->appendChild(new XMLElement('item', General::sanitize($e['message']))); } $result->appendChild($errors); $result->appendChild(new XMLElement('raw-data', General::wrapInCDATA($data))); } elseif (strlen(trim($ret)) == 0) { $this->_force_empty_result = true; } else { if ($this->dsParamCACHE > 0 && $writeToCache) { $cache->write($cache_id, $data, $this->dsParamCACHE); } $result->setValue(PHP_EOL . str_repeat("\t", 2) . preg_replace('/([\\r\\n]+)/', "\$1\t", $ret)); $result->setAttribute('status', $isCacheValid === true ? 'fresh' : 'stale'); $result->setAttribute('cache-id', $cache_id); $result->setAttribute('creation', $creation); } } } catch (Exception $e) { $result->appendChild(new XMLElement('error', $e->getMessage())); } if ($this->_force_empty_result) { $result = $this->emptyXMLSet(); } $result->setAttribute('url', General::sanitize($this->dsParamURL)); return $result; }
<h1>TCAT :: Export Tweets language</h1> <?php validate_all_variables(); /* @todo, use same export possibilities as mod.export_tweets.php */ $header = "id,time,created_at,from_user_name,from_user_lang,text,source,location,lat,lng,from_user_tweetcount,from_user_followercount,from_user_friendcount,from_user_realname,to_user_name,in_reply_to_status_id,quoted_status_id,from_user_listed,from_user_utcoffset,from_user_timezone,from_user_description,from_user_url,from_user_verified,filter_leveli,cld_name,cld_code,cld_reliable,cld_bytes,cld_percent"; if (isset($_GET['includeUrls']) && $_GET['includeUrls'] == 1) { $header .= ",urls,urls_expanded,urls_followed,domains"; } $header .= "\n"; $langset = $esc['mysql']['dataset'] . '_lang'; $sql = "SELECT * FROM " . $esc['mysql']['dataset'] . "_tweets t inner join {$langset} l on t.id = l.tweet_id "; $sql .= sqlSubset(); $sqlresults = mysql_query($sql); $filename = get_filename_for_export("fullExportLang"); $csv = new CSV($filename, $outputformat); $csv->writeheader(explode(',', $header)); if ($sqlresults) { while ($data = mysql_fetch_assoc($sqlresults)) { $csv->newrow(); if (preg_match("/_urls/", $sql)) { $id = $data['tweet_id']; } else { $id = $data['id']; } $csv->addfield($id); $csv->addfield(strtotime($data["created_at"])); $fields = array('created_at', 'from_user_name', 'from_user_lang', 'text', 'source', 'location', 'geo_lat', 'geo_lng', 'from_user_tweetcount', 'from_user_followercount', 'from_user_friendcount', 'from_user_realname', 'to_user_name', 'in_reply_to_status_id', 'quoted_status_id', 'from_user_listed', 'from_user_utcoffset', 'from_user_timezone', 'from_user_description', 'from_user_url', 'from_user_verified', 'filter_level'); foreach ($fields as $f) { $csv->addfield(isset($data[$f]) ? $data[$f] : ''); }
echo json_encode($editdata); exit; } elseif ($_GET['page'] === 'csv') { require_once FS_PHP . '/csv.php'; if (!isset($_GET['status'])) { $_GET["status"] = 0; } $data = $equip->listItems($SESSION->department, $_GET["status"]); if (sizeof($data)) { $output = new CSV($data); $output->generate(); } } elseif ($_GET['page'] === 'export-selected') { require_once FS_PHP . '/csv.php'; $data = $equip->listItemscsv(explode(',', $_GET['ids'])); $output = new CSV($data); $output->generate(); } else { require_once FS_PHP . '/error.php'; } //============================================================================================ // View //============================================================================================ $actions = array('add', 'edit', 'csv', 'export-selected', 'fetch'); if (isset($render) && $render) { $thisPage = "Keys"; if (isset($l10nFile) && file_exists($l10nFile)) { require $l10nFile; } require FS_PHP . '/header.php'; require FS_PHP . '/nav.php';
<script type="text/javascript" language="javascript"> </script> </head> <body> <h1>TCAT :: Tweet stats</h1> <?php validate_all_variables(); $filename = get_filename_for_export("tweetStats"); $csv = new CSV($filename, $outputformat); $numtweets = $numlinktweets = $numTweetsWithHashtag = $numTweetsWithMentions = $numTweetsWithMedia = $numRetweets = $numReplies = array(); // tweets in subset $sql = "SELECT count(distinct(t.id)) as count, "; $sql .= sqlInterval(); $sql .= " FROM " . $esc['mysql']['dataset'] . "_tweets t "; $sql .= sqlSubset(); $sql .= " GROUP BY datepart ORDER BY datepart ASC"; $sqlresults = mysql_unbuffered_query($sql); while ($data = mysql_fetch_assoc($sqlresults)) { $numtweets[$data['datepart']] = $data["count"]; } mysql_free_result($sqlresults); // tweet containing links $sql = "SELECT count(distinct(t.id)) AS count, "; $sql .= sqlInterval();
function generate($what, $filename) { global $tsv, $network, $esc, $titles, $database, $interval, $outputformat; require_once __DIR__ . '/CSV.class.php'; // initialize variables $tweets = $times = $from_user_names = $results = $urls = $urls_expanded = $hosts = $hashtags = array(); $csv = new CSV($filename, $outputformat); $collation = current_collation(); // determine interval $sql = "SELECT MIN(t.created_at) AS min, MAX(t.created_at) AS max FROM " . $esc['mysql']['dataset'] . "_tweets t "; $sql .= sqlSubset(); //print $sql . "<bR>"; $rec = mysql_query($sql); $res = mysql_fetch_assoc($rec); // get frequencies if ($what == "hashtag") { $results = frequencyTable("hashtags", "text"); } elseif ($what == "urls") { $results = frequencyTable("urls", "url_followed"); } elseif ($what == "hosts") { $results = frequencyTable("urls", "domain"); } elseif ($what == "mention") { $results = frequencyTable("mentions", "to_user"); // get other things } else { // @todo, this could also use database grouping $sql = "SELECT id,text COLLATE {$collation} as text,created_at,from_user_name COLLATE {$collation} as from_user_name FROM " . $esc['mysql']['dataset'] . "_tweets t "; $sql .= sqlSubset(); // get slice and its min and max time $rec = mysql_query($sql); if ($rec && mysql_num_rows($rec) > 0) { while ($res = mysql_fetch_assoc($rec)) { $tweets[] = $res['text']; $ids[] = $res['id']; $times[] = $res['created_at']; $from_user_names[] = strtolower($res['from_user_name']); } } // extract desired things ($what) and group per interval foreach ($tweets as $key => $tweet) { $time = $times[$key]; switch ($interval) { case "hourly": $group = strftime("%Y-%m-%d %Hh", strtotime($time)); break; case "weekly": $group = strftime("%Y %u", strtotime($time)); break; case "monthly": $group = strftime("%Y-%m", strtotime($time)); break; case "yearly": $group = strftime("%Y-%m", strtotime($time)); break; case "overall": $group = "overall"; break; case "custom": $group = groupByInterval(strftime("%Y-%m-%d", strtotime($time))); break; default: $group = strftime("%Y-%m-%d", strtotime($time)); // default daily } switch ($what) { //case "hashtag": // foreach ($hashtags as $hashtag) // $results[$group][] = $hashtag; // break; //case "mention": // @todo, mentions might be taken from own table // $stuff = get_replies($tweet); // foreach ($stuff as $thing) // $results[$group][] = $thing; // break; case "user": $results[$group][] = $from_user_names[$key]; break; case "user-mention": $stuff = get_replies($tweet); foreach ($stuff as $thing) { $results[$group]['mentions'][] = $thing; } $results[$group]['users'][] = $from_user_names[$key]; //var_dump($results); break; case "retweet": $results[$group][] = $tweet; // TODO, write stemming function break; //case "urls": // if (isset($urls_expanded[$ids[$key]])) // $results[$group][] = $urls_expanded[$ids[$key]]; // break; //case "hosts": // if (isset($urls_expanded[$ids[$key]])) // $results[$group][] = $hosts[$ids[$key]]; // break; //case "urls": // if (isset($urls_expanded[$ids[$key]])) // $results[$group][] = $urls_expanded[$ids[$key]]; // break; //case "hosts": // if (isset($urls_expanded[$ids[$key]])) // $results[$group][] = $hosts[$ids[$key]]; // break; default: break; } } // count frequency of occurence of thing, per interval if ($what != "user-mention") { foreach ($results as $group => $things) { $counted_things = array_count_values($things); arsort($counted_things); $results[$group] = $counted_things; } } } // network output for users if ($what == "user-mention") { foreach ($results as $group => $things) { $tmp_mentions = array_count_values($things['mentions']); $tmp_users = array_count_values($things['users']); $counted_things = array(); // add all from_user_names foreach ($tmp_users as $user => $count) { if (isset($tmp_mentions["@" . $user])) { $counted_things[$user] = $tmp_mentions["@" . $user] . "," . $count; } else { $counted_things[$user] = "0," . $count; } } // add all users which were replied but not in the set foreach ($tmp_mentions as $user => $count) { $user = str_replace("@", "", $user); if (!isset($counted_things[$user])) { $counted_things[$user] = $count . ",0"; } } ksort($counted_things); $results[$group] = $counted_things; } if (isset($titles[$what])) { if (!empty($esc['shell']['query'])) { $q = " with search " . $esc['shell']['query']; } else { $q = ""; } $csv->writeheader(array($titles[$what] . $q . " from " . $esc['date']["startdate"] . " to " . $esc['date']["enddate"])); } $csv->writeheader(array("date", "user", "mentions", "tweets")); foreach ($results as $group => $things) { foreach ($things as $thing => $count) { $csv->newrow(); $csv->addfield($group); $csv->addfield($thing); $exp = explode(",", $count); // unpack what we packed $csv->addfield($exp[0]); $csv->addfield($exp[1]); $csv->writerow(); } } // write tsv output } elseif (in_array($what, $tsv) !== false) { ksort($results); // construct file if (isset($titles[$what])) { if (!empty($esc['shell']['query'])) { $q = " with search " . $esc['shell']['query']; } else { $q = ""; } $csv->writeheader(array($titles[$what] . " for " . $esc['shell']['datasetname'] . $q . " from " . $esc['date']["startdate"] . " to " . $esc['date']["enddate"])); } if ($what == "urls") { $csv->writeheader(array("date", "frequency", "tweetedurl")); } elseif ($what == "hosts") { $csv->writeheader(array("date", "frequency", "domain", "name")); } else { $csv->writeheader(array("date", "frequency", $what)); } foreach ($results as $group => $things) { arsort($things); foreach ($things as $thing => $count) { if (empty($thing)) { continue; } if ($count < $esc['shell']['minf']) { continue; } $csv->newrow(); $csv->addfield($group); $csv->addfield($count); $csv->addfield($thing); $csv->writerow(); } } } else { die('no valid output format found'); } $csv->close(); }
<?php include_once 'dbconnect.php'; include_once 'dbtocsv.php'; $csv = new CSV(); $sql = "SELECT products_book_id, book_name, publisher_name, isbn_13, products_book.image\r\nFROM products_book\r\nLEFT JOIN publisher_master ON publisher_master.publisher_master_id = products_book.publisher_master_id\r\nWHERE products_book.image = ''\r\nOR products_book.image NOT LIKE '%.jpg'"; $csv->exportMysqlToCsv($sql);
/** * @name exportProduitCategorie($pParam) * @return CSV * @desc Retourne la liste des produits liés à la catégorie */ public function exportProduitCategorie($pParam) { $lVr = CategorieProduitValid::validDelete($pParam); if ($lVr->getValid()) { $lCategorie = CategorieProduitManager::select($pParam['id']); $lProduits = CatalogueFermeControleur::listeProduitCategorie($pParam['id']); $lCSV = new CSV(); $lCSV->setNom($lCategorie->getNom() . '_:_Liste_des_produits.csv'); // Le Nom // L'entete $lEntete = array("Nom du Produit"); $lCSV->setEntete($lEntete); $lContenuTableau = array(); foreach ($lProduits as $lProduit) { array_push($lContenuTableau, array($lProduit->getNom())); } $lCSV->setData($lContenuTableau); // Export en CSV $lCSV->output(); } return $lVr; }
/** * Exports CSV */ protected function renderCSV() { // exports orders if (Tools::isSubmit('csv_orders')) { $ids = array(); foreach ($this->_list as $entry) { $ids[] = $entry['id_supply_order']; } if (count($ids) <= 0) { return; } $id_lang = Context::getContext()->language->id; $orders = new PrestaShopCollection('SupplyOrder', $id_lang); $orders->where('is_template', '=', false); $orders->where('id_supply_order', 'in', $ids); $id_warehouse = $this->getCurrentWarehouse(); if ($id_warehouse != -1) { $orders->where('id_warehouse', '=', $id_warehouse); } $orders->getAll(); $csv = new CSV($orders, $this->l('supply_orders')); $csv->export(); } elseif (Tools::isSubmit('csv_orders_details')) { // header header('Content-type: text/csv'); header('Content-Type: application/force-download; charset=UTF-8'); header('Cache-Control: no-store, no-cache'); header('Content-disposition: attachment; filename="' . $this->l('supply_orders_details') . '.csv"'); // echoes details $ids = array(); foreach ($this->_list as $entry) { $ids[] = $entry['id_supply_order']; } if (count($ids) <= 0) { return; } // for each supply order $keys = array('id_product', 'id_product_attribute', 'reference', 'supplier_reference', 'ean13', 'upc', 'name', 'unit_price_te', 'quantity_expected', 'quantity_received', 'price_te', 'discount_rate', 'discount_value_te', 'price_with_discount_te', 'tax_rate', 'tax_value', 'price_ti', 'tax_value_with_order_discount', 'price_with_order_discount_te', 'id_supply_order'); echo sprintf("%s\n", implode(';', array_map(array('CSVCore', 'wrap'), $keys))); // overrides keys (in order to add FORMAT calls) $keys = array('sod.id_product', 'sod.id_product_attribute', 'sod.reference', 'sod.supplier_reference', 'sod.ean13', 'sod.upc', 'sod.name', 'FORMAT(sod.unit_price_te, 2)', 'sod.quantity_expected', 'sod.quantity_received', 'FORMAT(sod.price_te, 2)', 'FORMAT(sod.discount_rate, 2)', 'FORMAT(sod.discount_value_te, 2)', 'FORMAT(sod.price_with_discount_te, 2)', 'FORMAT(sod.tax_rate, 2)', 'FORMAT(sod.tax_value, 2)', 'FORMAT(sod.price_ti, 2)', 'FORMAT(sod.tax_value_with_order_discount, 2)', 'FORMAT(sod.price_with_order_discount_te, 2)', 'sod.id_supply_order'); foreach ($ids as $id) { $query = new DbQuery(); $query->select(implode(', ', $keys)); $query->from('supply_order_detail', 'sod'); $query->leftJoin('supply_order', 'so', 'so.id_supply_order = sod.id_supply_order'); $id_warehouse = $this->getCurrentWarehouse(); if ($id_warehouse != -1) { $query->where('so.id_warehouse = ' . (int) $id_warehouse); } $query->where('sod.id_supply_order = ' . (int) $id); $query->orderBy('sod.id_supply_order_detail DESC'); $resource = Db::getInstance()->query($query); // gets details while ($row = Db::getInstance()->nextRow($resource)) { echo sprintf("%s\n", implode(';', array_map(array('CSVCore', 'wrap'), $row))); } } } elseif (Tools::isSubmit('csv_order_details') && Tools::getValue('id_supply_order')) { $supply_order = new SupplyOrder((int) Tools::getValue('id_supply_order')); if (Validate::isLoadedObject($supply_order)) { $details = $supply_order->getEntriesCollection(); $details->getAll(); $csv = new CSV($details, $this->l('supply_order') . '_' . $supply_order->reference . '_details'); $csv->export(); } } }
function saveToCSV() { $csv = new CSV("./output/csv/" . $this->output . ".csv"); $csv->addArrayHeader(array("trcid", "title", "shortdescription", "longdescription", "calendarsummary", "titleEN", "shortdescriptionEN", "longdescriptionEN", "calendarsummaryEN", "types", "ids", "locatienaam", "city", "adres", "zipcode", "latitude", "longitude", "urls", "media", "thumbnail", "datepattern_startdate", "datepattern_enddate", "singledates", "lastupdated")); foreach ($this->items as $item) { $csv->addArray($item); } if ($this->append) { $csv->append(); } else { $csv->write(); } $this->debug("Saved as CSV (" . $this->output . ")"); }
<script type="text/javascript" language="javascript"> </script> </head> <body> <h1>TCAT :: User Stats</h1> <?php validate_all_variables(); $filename = get_filename_for_export("userStats"); $csv = new CSV($filename, $outputformat); // tweets per user $sql = "SELECT count(distinct(t.id)) AS count, t.from_user_id, "; $sql .= sqlInterval(); $sql .= " FROM " . $esc['mysql']['dataset'] . "_tweets t "; $sql .= sqlSubset(); $sql .= "GROUP BY datepart, from_user_id"; //print $sql . "<br>"; $sqlresults = mysql_unbuffered_query($sql); $array = array(); while ($res = mysql_fetch_assoc($sqlresults)) { $array[$res['datepart']][$res['from_user_id']] = $res['count']; } mysql_free_result($sqlresults); if (!empty($array)) { foreach ($array as $date => $ar) {
// make filename and open file for write $module = "gapData"; $sql = "SELECT id, `type` FROM tcat_query_bins WHERE querybin = '" . mysql_real_escape_string($esc['mysql']['dataset']) . "'"; $sqlresults = mysql_query($sql); if ($res = mysql_fetch_assoc($sqlresults)) { $bin_id = $res['id']; $bin_type = $res['type']; } else { die("Query bin not found!"); } $exportSettings = array(); if (isset($_GET['exportSettings']) && $_GET['exportSettings'] != "") { $exportSettings = explode(",", $_GET['exportSettings']); } $filename = get_filename_for_export($module, implode("_", $exportSettings)); $csv = new CSV($filename, $outputformat); // write header $header = "start,end"; $csv->writeheader(explode(',', $header)); // make query $sql = "SELECT * FROM tcat_error_gap WHERE type = '" . mysql_real_escape_string($bin_type) . "' and\n start >= '" . mysql_real_escape_string($_GET['startdate']) . "' and end <= '" . mysql_real_escape_string($_GET['enddate']) . "'"; // loop over results and write to file $sqlresults = mysql_query($sql); if ($sqlresults) { while ($data = mysql_fetch_assoc($sqlresults)) { // the query bin must have been active during the gap period, if we want to report it as a possible gap $sql2 = "SELECT count(*) as cnt FROM tcat_query_bins_phrases WHERE querybin_id = {$bin_id} and\n starttime <= '" . $data["end"] . "' and (endtime >= '" . $data["start"] . "' or endtime is null or endtime = '0000-00-00 00:00:00')"; $sqlresults2 = mysql_query($sql2); if ($sqlresults2) { if ($data2 = mysql_fetch_assoc($sqlresults2)) { if ($data2['cnt'] > 0) {
$fileName = $_FILES["myfile"]["name"]; //file name $fileTmpLoc = $_FILES["myfile"]["tmp_name"]; //file in the php tmp folder $fileType = $_FILES["myfile"]["type"]; //file type $fileSize = $_FILES["myfile"]["size"]; //file size $fileErrorMsg = $_FILES["myfile"]["error"]; //0 for false and 1 for true if (!$fileTmpLoc) { die(new ModelResponse(false, 'Please browse for a valid file')); } $destPath = "{$uploadPath}/{$fileName}"; if (move_uploaded_file($fileTmpLoc, $destPath)) { $raw_data = CSV::Parse($destPath); // Get initial user list $currentUserList = new Models\UserList(); // Initialize container $userList = new Models\UserList(false); // proceed with creation foreach ($raw_data as $row) { $user = new Models\User(); if ($currentUserList->ContainsUsername($row['username'])) { $user = \Models\User::FindUsername(strtolower(trim($row['username']))); } else { $user->Absorb($row); } $userList->add($user); } if (!$userList->Create()) {
$requetefinale = str_replace(table_subscribers, $prefix . "subscribers", $requetebrute); $requetefinale = str_replace(table_subscriber_id, $prefix . "subscribers.subscriber_id", $requetefinale); $requetefinale = str_replace(table_subscriber_email, $prefix . "subscribers.email", $requetefinale); $requetefinale = str_replace(table_mailings, $prefix . "mailings", $requetefinale); $requetefinale = str_replace(table_mailing_id, $prefix . "mailings.mailing_id", $requetefinale); $requetefinale = str_replace(table_mailing_started, $prefix . "mailings.started", $requetefinale); $requetefinale = str_replace(table_mailing_sent, $prefix . "mailings.sent", $requetefinale); $requetefinale = str_replace(table_mailing_subject, $prefix . "mailings.subject", $requetefinale); $requetefinale = str_replace(table_mailing_mailgroup, $prefix . "mailings.mailgroup", $requetefinale); $requetefinale = str_replace(table_opentracking, $prefix . "opentracking", $requetefinale); // Pour vérifier la requete, décommenter la ligne ci-dessous. // print $requetefinale; // La 2nde requete est fin prete: nous allons maintenant l'exécuter... $result = NULL; $result = $id_connex->query($requetefinale); if (!$result) { echo "<meta http-equiv=\"refresh\" content=\"0;URL=tracking_opening_menu.php\">"; } $data = $result->fetchAll(); // print_r($data); $datas = array(); foreach ($data as $d) { $datas[] = array('ID Mail' => $d[mailing_id], 'Titre du message' => $d[subject], 'Groupe' => $d[mailgroup], 'Heure d\'envoi' => $d[started], 'Heure d\'ouverture' => $d[dateouverture], 'Latence (heures)' => $d[latence], 'Email' => $d[email]); } require 'exportcsv.class.php'; CSV::export($datas, 'pommo_ouvertures_details'); // print_r($datas); } else { echo "<meta http-equiv=\"refresh\" content=\"0;URL=tracking_opening_menu.php\">"; } Pommo::kill();