function up() { echo "Starting Migration Proc ...<BR>"; //check if migration already had ran ... $migration = Migration::get()->filter('Name', $this->title)->first(); $promo_code_type = isset($_REQUEST['promo_code_type']) ? intval($_REQUEST['promo_code_type']) : null; $promo_code_file = isset($_REQUEST['promo_code_file']) ? $_REQUEST['promo_code_file'] : null; if (is_null($promo_code_type)) { echo 'ERROR - promo_code_type param missing!'; exit; } if (is_null($promo_code_file)) { echo 'ERROR - promo_code_file param missing!'; exit; } $base_path = ASSETS_PATH; $file_path = $base_path . '/' . $promo_code_file; $type = explode(".", $file_path); if (!strtolower(end($type)) == 'csv') { echo 'ERROR - file hast not a csv extension!'; exit; } if (!file_exists($file_path)) { echo sprintf('ERROR - %s file does not exists!', $file_path); exit; } $reader = new CSVReader($file_path); $row = 0; do { $line = $reader->getLine(); if ($line) { ++$row; if ($row === 1) { continue; } // skip header ... switch ($promo_code_type) { case 1: $type = 'ACCEPTED'; break; case 2: $type = 'ALTERNATE'; break; } $code = new SpeakerSummitRegistrationPromoCode(); $code->Code = $line[0]; $code->Type = $type; $code->SummitID = Summit::get_active()->ID; try { $code->write(); } catch (Exception $ex) { SS_Log::log($ex->getMessage(), SS_Log::ERR); } } } while ($line); echo "Ending Migration Proc ...<BR>"; }
function getDataFromCsvFile($options) { $filename = $this->getFilename($options); $path = $this->getCsvPath($filename); $csv = new CSVReader(); $csv->useHeaderAsIndex(); $this->setRow($csv, $options); return $csv->getData($path); }
public function control() { $this->redirectToSternIndiaEndPoint(); $config = Config::getInstance(); if (isset($_POST['upload']) && $_POST['upload'] == 'Upload') { $target_dir = new FileSystem('upload/'); $file = new File('foo', $target_dir); $name = date('D_d_m_Y_H_m_s_'); $name = $name . $file->getName(); $file->setName($name); $config = Config::getInstance(); $file->addValidations(array(new Mimetype($config->getMimeTypes()), new Size('5M'))); $data = array('name' => $file->getNameWithExtension(), 'extension' => $file->getExtension(), 'mime' => $file->getMimetype(), 'size' => $file->getSize(), 'md5' => $file->getMd5()); try { // /Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__,$data); $file->upload(); //Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__,$data); } catch (Exception $e) { $errors = $file->getErrors(); } $csvReader = new CSVReader(); $destinationFile = $target_dir->directory . $file->getNameWithExtension(); $data = $csvReader->parse_file($destinationFile); //$country= DAOFactory::getDAO('LocationDAO'); foreach ($data as $loc_arr) { Utils::processLocation($loc_arr); } //Profiler::debugPoint(true,__METHOD__, __FILE__, __LINE__); $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]); $uploadOk = 1; $imageFileType = pathinfo($target_file, PATHINFO_EXTENSION); // Check if image file is a actual image or fake image if (isset($_POST["submit"])) { $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]); if ($check !== false) { echo "File is an image - " . $check["mime"] . "."; $uploadOk = 1; } else { echo "File is not an image."; $uploadOk = 0; } } } return $this->generateView(); }
public function MigrateCustomer() { $resultSetArr = CSVReader::csvToArray(public_path() . DIRECTORY_SEPARATOR . "product.csv", ","); if (count($resultSetArr > 0)) { foreach ($resultSetArr as $cusInfo) { } DB::table('orocrm_magento_customer')->insert(array('website_id' => 1, 'store_id' => 1, 'customer_group_id' => 1, 'channel_id' => 1, 'data_channel_id' => 3, 'organization_id' => 1, 'first_name' => 'Cedric', 'last_name' => 'Mui', 'gender' => 'male', 'birthday' => '1987-01-01', 'email' => '*****@*****.**', 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), 'is_active' => 1, 'currency' => 'SGD', 'origin_id' => 999, 'is_confirmed' => 1, 'is_guest' => 0)); echo "It's look good. Customer migration is completed."; } else { echo "No CSV data found"; } }
function csvImporter($csvfile) { $_SESSION['uid'] = $this->libFunc->ifSet($_SESSION, 'uid', ""); $itemstring = ""; $log = ""; $itemCount = 0; $successCount = 0; #Initial number of intert and update product $totalUpdate = 0; $totalInsert = 0; $itemArray = array(); $reader = new CSVReader(new FileReader($csvfile)); $reader->setSeparator($this->request['delimiter']); $line = 0; #GETTING TOTAL COLUMNS SELECTED foreach ($this->request['item'] as $item) { if (!empty($item) && !in_array($item, $itemArray)) { array_push($itemArray, $item); if ($item == "vSupplier_name") { $item = "iVendorid_FK"; } $itemstring .= $item . ","; $itemCount++; } } $itemstring = substr($itemstring, 0, -1); $query = "INSERT INTO " . PRODUCTS . " ({$itemstring},`tmBuildDate`,`iAdminUser`) VALUES("; # READ THROUGH THE CSV FILE while (false != ($cell = $reader->next())) { $queryUPDATE = " UPDATE " . PRODUCTS . " SET "; $skip = 0; $valueString = ""; $reason = ""; $title = ""; #echo"<pre>"; #print_r($cell)."<br />"; #echo"</pre><br />"; #echo "item count =".$itemCount; #echo "count cell =".count($cell); if ($itemCount != count($cell)) { $skip = 1; $reason = "Column Mismatch in the line number " . $line; } else { #FOR EACH ELEMENT FROM THE LINE NEED TO BE ASSOCIATE AND ORDERD WITH IMPORTER DROP-DOWN LIST for ($i = 0; $i < $itemCount; $i++) { #echo $cell[$i]." -------> ".$this->request['item'][$i]." "; if ($this->request['item'][$i] == 'vTitle') { if (!isset($cell[$i]) || empty($cell[$i])) { $skip = 1; $reason = "<br /><b>Title empty</b>"; $title = ""; } else { $title = $cell[$i]; } } elseif ($this->request['item'][$i] == 'vSku') { if (!isset($cell[$i]) || empty($cell[$i])) { $skip = 1; $reason = "<br /><b>SKU empty</b>"; } else { $sku = $cell[$i]; } } elseif ($this->request['item'][$i] == 'fPrice') { if (!isset($cell[$i]) || empty($cell[$i])) { $skip = 1; $reason = "<br /><b>Price empty or not valid</b>"; } else { $price = $cell[$i]; } } elseif ($this->request['item'][$i] == 'vSeoTitle') { if (!isset($cell[$i]) || empty($cell[$i])) { if (empty($title)) { $skip = 1; $reason = "<br /><b>Seo Title empty</b>"; } } else { $seoTitle = $cell[$i]; } } if (isset($cell[$i])) { if ($itemArray[$i] == "vSupplier_name") { # RETRIEVE SUPPLIER ID BASED ON SUPPLIER NAME $this->obDb->query = " SELECT iVendorid_PK FROM " . SUPPLIERS . " WHERE vCompany = '" . $this->libFunc->m_addToDB($cell[$i]) . "'"; $supRow = $this->obDb->fetchQuery(); if ($this->obDb->record_count > 0) { $supplierID = $supRow[0]->iVendorid_PK; } else { $supplierID = 0; } $valueString .= "'" . $this->libFunc->m_addToDB($cell[$i]) . "',"; $queryUPDATE .= " iVendorid_FK = '" . $supplierID . "',"; } else { $valueString .= "'" . $this->libFunc->m_addToDB($cell[$i]) . "',"; $queryUPDATE .= " " . $itemArray[$i] . " = '" . $this->libFunc->m_addToDB($cell[$i]) . "',"; } } else { $valueString .= "' ',"; } } #END FOR } #END IF SKIP if ($skip == 1) { $valueString1 = substr($valueString, 0, -1); if (strlen($valueString1) > 50) { $valueString1 = substr($valueString1, 0, 50) . "..."; } $log .= $this->libFunc->m_displayContent($valueString1) . $reason . "<br>"; } else { $timeStamp = time(); $valueString1 = substr($valueString, 0, -1); # Insert The SESSION ID $query1 = $query . $valueString1 . "," . $timeStamp . ",'" . $_SESSION['uid'] . "')"; $successCount++; $queryUPDATE .= "tmBuildDate =" . $timeStamp . ",\n\t\t\t\t\t\t\t iAdminUser ="******" WHERE "; # CHECK IF THE PRODUCT SEO TITLE ALREADY EXIST IN DATABASE $this->obDb->query = "SELECT * FROM " . PRODUCTS . " \n\t\t\t\t\t\t\t\t\t WHERE vSeoTitle='" . $this->libFunc->m_addToDB($seoTitle) . "'\t\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t \t\n\t\t\t\t\t\t\t\t\t "; # YOU CAN ADD MORE FIELDS TO THE CONDITION AS BELOW /* AND vSku = '".$this->libFunc->m_addToDB($sku)."' AND vTitle = '".$this->libFunc->m_addToDB($title)."' AND fPrice = ".$this->libFunc->m_addToDB($price)." */ $resCnt = $this->obDb->fetchQuery(); $resCntCount = $this->obDb->record_count; if ($resCntCount > 0) { # DO THE UPDATE $this->obDb->query = "SELECT iProdid_PK FROM " . PRODUCTS . " \n\t\t\t\t\t\t\t\t\t\t WHERE vSeoTitle='" . $this->libFunc->m_addToDB($seoTitle) . "'"; $rowPK = $this->obDb->fetchQuery(); $queryUPDATE .= " iProdid_PK =" . $rowPK[0]->iProdid_PK; $this->obDb->query = $queryUPDATE; $this->obDb->execQry($this->obDb->query); $totalUpdate++; } else { # DO THE INSERT $this->obDb->query = $query1; $this->obDb->updateQuery(); $subObjId = $this->obDb->last_insert_id; $this->obDb->query = "UPDATE " . PRODUCTS . " SET vTemplate='" . $this->request['template'] . "' ,vLayout='" . $this->request['layout'] . "',iCartButton ='1' WHERE iProdId_PK='{$subObjId}'"; $this->obDb->updateQuery(); #Increase totalInsert by 1 if ($this->obDb->last_insert_id > 0) { $totalInsert++; } #GETTING MAXIMUM SOR UNDER INSERTED OWNER $this->obDb->query = "select MAX(iSort) AS MaxSort\n\t\t\t\t\tfrom " . FUSIONS . "\twhere iOwner_FK = " . $this->request['department'] . " and vOwnerType = 'department' and vType ='product'"; $res = $this->obDb->fetchQuery(); $sort = $res[0]->MaxSort + 1; #INSERTING TO FUSIONS TABLE $this->obDb->query = "insert into " . FUSIONS . "\n\t\t\t\t\t(`fusionId`, `iOwner_FK`, `iSubId_FK`,`vtype`, `iSort`, `iState`,`vOwnerType`)\n\t\t\t\t\tvalues(''," . $this->request['department'] . ",'{$subObjId}','product','{$sort}','1','department')"; $this->obDb->updateQuery(); } } $line++; #POINT TO THE NEXT LINE $cell = $reader->next(); } #END WHILE unlink($csvfile); if ($successCount == 0) { $hint = "<br />Please ensure that you had selected correct delimiter.<br />Total number of columns in CSV should be greater than or equal to fields selected by you."; } else { $hint = ""; } $_SESSION['status'] = $successCount . " products successfully uploaded <br />" . $log . $hint; $_SESSION['csvUpdatedTotal'] = $totalUpdate; $_SESSION['csvInsertedTotal'] = $totalInsert; $this->libFunc->m_mosRedirect(SITE_URL . "admin/adminindex.php?action=csv.dspmsg"); exit; }
function readCsvFile($path) { $csv = new CSVReader(); $csv->useHeaderAsIndex(); return $csv->data($path); }
/** * @return int */ public function processFiles() { $coa_file_api = $this->coa_file_api; $member_repository = $this->member_repository; $exam_repository = $this->exam_repository; $factory = $this->factory; return $this->tx_manager->transaction(function () use($coa_file_api, $member_repository, $exam_repository, $factory) { try { $files = $coa_file_api->getFilesList(); $processed_files = 0; foreach ($files as $file_info) { if ($this->isFileProcessed($file_info)) { continue; } $content = $coa_file_api->getFileContent($file_info['filename']); $rows = CSVReader::load($content); foreach ($rows as $row) { $exam_ext_id = $row['candidate_exam_id']; $modified_date = $row['candidate_exam_date_modified']; // this groups all candidate exams attempts together ... $track_id = $row['certification_track_status_id']; $track_id_modified_date = $row['certification_track_status_date_modified']; $candidate_name = $row['candidate_exam_name']; $candidate_fname = $row['first_name']; $candidate_lname = $row['last_name']; $email = $row['open_stack_id']; $exam_expiration_date = $row['exam_expiration_date']; $status = $row['exam_status']; $pass_date = $row['pass_fail_date_c']; $cert_nbr = $row['certification_number']; $code = $row['exam_code']; $cert_status = $row['certification_status']; $cert_exam_expiration_date = $row['certificate_expiration_date']; $member = null; // first attempt, try to find member by email ... if (!empty($email)) { $member = $member_repository->findByEmail($email); } // second attempt, try to find member by former exams if (is_null($member)) { // possible a retake ? check by $track_id $former_exams = $exam_repository->getByTrackId($track_id); foreach ($former_exams as $former_exam) { if ($former_exam->hasOwner()) { $member = $former_exam->Owner(); break; } } } // we werent able to find member ... skip it if (is_null($member)) { continue; } // try to find if we have a former exam ... $exam = $member->getExamByExternalId($exam_ext_id); if (is_null($exam)) { $exam = $factory->build($member, $exam_ext_id); } $exam->setState($track_id, $track_id_modified_date, $candidate_name, $candidate_fname, $candidate_lname, $status, $modified_date, $exam_expiration_date, $pass_date, $code, $cert_nbr, $cert_exam_expiration_date, $cert_status); $exam->write(); } $this->markFileAsProcessed($file_info); $processed_files++; } return $processed_files; } catch (Exception $ex) { SS_Log::log($ex->getMessage(), SS_Log::WARN); throw $ex; } }); }
switch ($_REQUEST['existing']) { case 'replace': $existing = 'replace'; break; case 'ignore': $existing = 'ignore'; break; default: $existing = 'replace'; break; } // ======================================================== // Datei цffnen // ======================================================== $fp = fopen($TempDir . '/CSVIMPORT_user_' . $_SESSION['user_id'] . '_' . $fileid . '.txt', 'r'); $csv = new CSVReader($fp); $fields = $csv->Fields(); if ($error == true) { $AVE_Template->assign('content', $tpl_in); } while ($row = $csv->FetchRow()) { if (count($row) == $csv->NumFields()) { $Id = ''; $password = ''; $email = ''; $street = ''; $street_nr = ''; $zipcode = ''; $City = ''; $phone = ''; $telefax = '';
switch ($_REQUEST['existing']) { case 'replace': $existing = 'replace'; break; case 'ignore': $existing = 'ignore'; break; default: $existing = 'replace'; break; } // ======================================================== // Datei цffnen // ======================================================== $fp = fopen($TempDir . '/CSVIMPORT_shop_' . $_SESSION['user_id'] . '_' . $fileid . '.txt', 'r'); $csv = new CSVReader($fp); $fields = $csv->Fields(); if ($error == true) { echo 'FEHLER'; $AVE_Template->assign('content', $tpl_in); } while ($row = $csv->FetchRow()) { if (sizeof($row) == $csv->NumFields()) { $Id = ''; $ArtNr = ''; $KatId = ''; $KatId_Multi = ''; $ArtName = ''; $status = ''; $Preis = ''; $PreisListe = '';
/** * @return string */ public function getContent() { $ok = null; if (Tools::isSubmit('submitShipping')) { $handle = new CSVReader(Tools::getValue("filename"), $_FILES['PINCODE_UPLOAD']['tmp_name']); if ($handle->iscsvUpload()) { $shipping = Tools::getValue('SHIPPING_METHOD'); if (isset($shipping) && Validate::isCarrierName((string) $shipping)) { Configuration::updateValue('SHIPPING_METHOD', (string) $shipping); $this->updateCODPincode($handle->getRows(), $shipping); $ok = true; } else { $this->_html .= $this->displayError($this->l('Error occurred during Shipping Pincode update')); } } else { $this->_html .= $this->displayError(CSVconst::UPLOAD_ERROR); } } else { if (Tools::isSubmit('submitCOD')) { $cod_min = Tools::getValue('COD_MINIMUM_AMOUNT'); $cod_fee = Tools::getValue('COD_FEE'); if (isset($cod_min) && isset($cod_fee) && Validate::isFloat((double) $cod_min) && Validate::isFloat((double) $cod_fee)) { Configuration::updateValue('COD_MINIMUM_AMOUNT', (string) $cod_min); Configuration::updateValue('COD_FEE', (string) $cod_fee); $ok = true; } else { $this->_html .= $this->displayError($this->l('Error occurred during COD update')); } } } if ($ok) { $this->_html .= $this->displayConfirmation($this->l('Settings updated succesfully')); } $this->_html .= $this->renderForm(); return $this->_html; }
/** * @expectedException Exception * @expectedExceptionMessage Invalid CSV header. Make sure your column header is "phone_number". */ public function test__survey_respondents_import_check__file_no_header() { // Load CSVReader library. $csv = new CSVReader(); $csv->separator = ','; $rows = $csv->parse_file(ROOT_PATH . 'tests/test_resources/respondents_csv/10_valid_no_header.csv'); // From DB $db_call_tasks = array(); $respondents = self::$CI->_survey_respondents_import_check($rows, $db_call_tasks); }
public static function importFile(&$descriptior) { $timeLimit = ini_get('max_execution_time'); if ($timeLimit < $descriptior['TIME_LIMIT']) { set_time_limit($descriptior['TIME_LIMIT'] + 5); } $endTime = time() + $descriptior['TIME_LIMIT']; if ($descriptior['STEP'] == 'rebalance') { Location\LocationTable::resort(); $descriptior['STEP'] = 'done'; } if ($descriptior['STEP'] == 'import') { if (!isset($descriptior['DO_SYNC'])) { $res = \Bitrix\Sale\Location\LocationTable::getList(array('select' => array('CNT')))->fetch(); $descriptior['DO_SYNC'] = intval($res['CNT'] > 0); } if (!isset($descriptior['TYPES'])) { $descriptior['TYPES'] = static::getExistedTypes(); $descriptior['SERVICES'] = static::getExistedServices(); $descriptior['TYPE_MAP'] = static::getTypeMap($descriptior['TYPE_FILE']); $descriptior['SERVICE_MAP'] = static::getServiceMap($descriptior['SERVICE_FILE']); } $csvReader = new CSVReader(); $csvReader->LoadFile($descriptior['FILE']); while (time() < $endTime) { $block = $csvReader->ReadBlockLowLevel($descriptior['POS'], 100); if (!count($block)) { break; } foreach ($block as $item) { if (!isset($descriptior['TYPES'][$item['TYPE_CODE']])) { $descriptior['TYPES'][$item['TYPE_CODE']] = static::createType($descriptior['TYPE_MAP'][$item['TYPE_CODE']]); } if ($descriptior['DO_SYNC']) { $id = static::checkLocationCodeExists($item['CODE']); if ($id) { $descriptior['CODES'][$item['CODE']] = $id; continue; } } // type $item['TYPE_ID'] = $descriptior['TYPES'][$item['TYPE_CODE']]; unset($item['TYPE_CODE']); // parent id if (strlen($item['PARENT_CODE'])) { if (!isset($descriptior['CODES'][$item['PARENT_CODE']])) { $descriptior['CODES'][$item['PARENT_CODE']] = static::checkLocationCodeExists($item['PARENT_CODE']); } $item['PARENT_ID'] = $descriptior['CODES'][$item['PARENT_CODE']]; } unset($item['PARENT_CODE']); // ext if (is_array($item['EXT'])) { foreach ($item['EXT'] as $code => $values) { if (is_array($values) && !empty($values)) { if (!isset($descriptior['SERVICES'][$code])) { $descriptior['SERVICES'][$code] = static::createService(array('CODE' => $code)); } foreach ($values as $value) { if (!strlen($value)) { continue; } $item['EXTERNAL'][] = array('SERVICE_ID' => $descriptior['SERVICES'][$code], 'XML_ID' => $value); } } } } unset($item['EXT']); $res = Location\LocationTable::add($item, array('REBALANCE' => false)); if (!$res->isSuccess()) { throw new Main\SystemException('Cannot create location'); } $descriptior['CODES'][$item['CODE']] = $res->getId(); } } if (!count($block)) { unset($descriptior['CODES']); $descriptior['STEP'] = 'rebalance'; } } return $descriptior['STEP'] == 'done'; }
/** * @param string $filename * @param int $election_id * @param DateTime $open_date * @param DateTime $close_date * @return array */ public function ingestVotersForElection($filename, $election_id, DateTime $open_date, DateTime $close_date) { $election_repository = $this->election_repository; $foundation_member_repository = $this->foundation_member_repository; $vote_factory = $this->vote_factory; $vote_repository = $this->vote_repository; $voter_file_factory = $this->voter_file_factory; $voter_file_repository = $this->voter_file_repository; $election_factory = $this->election_factory; return $this->tx_manager->transaction(function () use($filename, $election_id, $open_date, $close_date, $election_repository, $foundation_member_repository, $vote_factory, $vote_repository, $voter_file_factory, $voter_file_repository, $election_factory) { if ($voter_file_repository->getByFileName($filename)) { throw new EntityAlreadyExistsException('VoterFile', sprintf('filename = %s', $filename)); } $election = $election_repository->getById($election_id); if (!$election) { $election = $election_factory->build($election_id, $open_date, $close_date); $election_repository->add($election); } $reader = new CSVReader($filename); $line = false; $header = $reader->getLine(); $count = 0; $not_processed = array(); while ($line = $reader->getLine()) { $first_name = $line[1]; $last_name = $line[2]; $member_id = (int) $line[3]; $member = $foundation_member_repository->getById($member_id); if (!$member) { $member = $foundation_member_repository->getByCompleteName($first_name, $last_name); } if ($member && $member->isFoundationMember()) { $vote = $vote_factory->buildVote($election, $member); $vote_repository->add($vote); $count++; } else { array_push($not_processed, array('id' => $member_id, 'first_name' => $first_name, 'last_name' => $last_name)); } } $voter_file = $voter_file_factory->build($filename); $voter_file_repository->add($voter_file); return array($count, $not_processed); }); }
/** * Summary page to add respondents to a given survey. * @param $sid * * Route - /survey/:sid/respondents/(file|input) */ public function survey_respondents_add($sid, $type) { $survey = $this->survey_model->get($sid); if (!$survey) { show_404(); } else { if (!has_permission('manage respondents any survey')) { show_403(); } } if (!$survey->status_allows('import respondents any survey')) { show_403(); } // Form validation based on import type. switch ($type) { case 'file': // Config data for the file upload. $file_upload_config = array('upload_path' => '/tmp/', 'allowed_types' => 'csv', 'file_name' => 'respondents_' . md5(microtime(true))); // Load needed libraries. $this->load->library('upload', $file_upload_config); $this->form_validation->set_rules('survey_respondents_file', 'Respondents File', 'callback__cb_survey_respondents_add_file_handle'); break; case 'direct': $this->form_validation->set_rules('survey_respondents_text', 'Respondents Text', 'trim|required|xss_clean'); break; } $this->form_validation->set_error_delimiters('<small class="error">', '</small>'); // If the import has invalid respondents they are added to the textarea // to allow the user to correct them. $invalid_respondents = array(); if (isset($_SESSION['respondents_numbers']['invalid'])) { $invalid_respondents = $_SESSION['respondents_numbers']['invalid']; // Unset so they don't bother anymore. unset($_SESSION['respondents_numbers']); } // If no data submitted show the form. if ($this->form_validation->run() == FALSE) { $this->load->view('base/html_start'); $this->load->view('components/navigation', array('active_menu' => 'surveys')); $this->load->view('surveys/survey_respondents_add', array('survey' => $survey, 'import_type' => $type, 'invalid_respondents' => $invalid_respondents)); $this->load->view('base/html_end'); } else { // Processing based on import type. switch ($type) { case 'file': // Read file. $file = $this->input->post('survey_respondents_file'); if (isset($file['full_path'])) { // Load CSVReader library. $this->load->helper('csvreader'); $csv = new CSVReader(); $csv->separator = ','; $rows = $csv->parse_file($file['full_path']); } break; case 'direct': $rows = explode("\n", $this->input->post('survey_respondents_text')); break; } if (!isset($rows)) { Status_msg::error('An error occurred when processing the numbers. Try again.'); redirect($survey->get_url_respondents()); } // Load all call_tasks from DB to check for duplicates. $db_call_tasks = $this->call_task_model->get_all($sid); try { $respondents_numbers = $this->_survey_respondents_import_check($rows, $db_call_tasks); } catch (Exception $e) { Status_msg::error($e->getMessage()); redirect($survey->get_url_respondents()); } // Create a call_task for each respondent number. $success_saves = array(); foreach ($respondents_numbers['valid'] as $number) { // Prepare survey data to construct a new survey_entity $call_task_data = array(); $call_task_data['survey_sid'] = (int) $sid; $call_task_data['number'] = (string) $number; // Construct survey. $new_call_task = Call_task_entity::build($call_task_data); // Save call task. if ($this->call_task_model->save($new_call_task)) { $success_saves[] = $number; } else { // If an error occurred flag as invalid to be imported again. // This should not happen, but you never know. $respondents_numbers['invalid'][] = $number; } } $respondents_numbers['valid'] = $success_saves; // Setting messages. $total_valid = count($respondents_numbers['valid']); $total_invalid = count($respondents_numbers['invalid']); $total_dups = count($respondents_numbers['dups']); $total_numbers = $total_valid + $total_invalid + $total_dups; if ($total_valid) { Status_msg::success("{$total_valid} of {$total_numbers} respondents were successfully imported.", TRUE); } else { Status_msg::warning("No respondents were imported."); } if ($total_invalid) { Status_msg::error("{$total_invalid} of {$total_numbers} respondents were not in a valid format."); } if ($total_dups) { Status_msg::notice("{$total_dups} of {$total_numbers} respondents have duplicate phone numbers."); } // Store invalid in any. if ($total_invalid) { $_SESSION['respondents_numbers']['invalid'] = $respondents_numbers['invalid']; redirect($survey->get_url_respondents_add('direct')); } redirect($survey->get_url_respondents()); } }
<?php require_once 'libs/csv-reader.php'; $exampleFile = "data/example.csv"; $driverFile = "data/driver.csv"; $csvReader = new CSVReader(); $example = $csvReader->Get($exampleFile); $drivers = $csvReader->Get($driverFile, true); // echo json_encode($example); echo json_encode($drivers);