/** * コンストラクタ * */ public function __construct() { $this->log = LoggerManager::getLogger(get_class($this)); $request = array_merge($_POST, $_GET); if (get_magic_quotes_gpc()) { $request = $this->_stripSlashesDeep($request); } if (!ini_get("mbstring.encoding_translation") && INPUT_CODE != INTERNAL_CODE) { mb_convert_variables(INTERNAL_CODE, INPUT_CODE, $request); } // action:~ではじまるパラメータがあればactionMethodをセットする $methodName = "execute"; $key = NULL; foreach ($request as $k => $val) { if (preg_match('/^action:(.+)$/', $k, $m)) { $methodName = $m[1]; $this->log->debug("actionMethodが指定されました。 {$methodName}"); $key = $k; break; } } $this->actionMethod = $methodName; if ($key != NULL) { unset($request[$key]); } $this->_params = $request; return; }
public function loadDataCsv($fileName, $column_list, $delimiter = ",", $array_encoding = 'utf8', $import_encoding = 'sjis-win') { //保存をするのでモデルを読み込み try { $data = array(); $csvData = array(); $file = fopen($fileName, "r"); while ($data = $this->fgetcsv_reg($file, 65536, $delimiter)) { //CSVファイルを","区切りで配列に mb_convert_variables($array_encoding, $import_encoding, $data); $csvData[] = $data; } $i = 0; foreach ($csvData as $line) { $this_data = array(); foreach ($column_list as $k => $v) { if (isset($line[$k])) { //先頭と末尾の"を削除 $b = $line[$k]; //カラムの数だけセット $this_data = Hash::merge($this_data, array($v => $b)); } else { $this_data = Hash::merge($this_data, array($v => '')); } } $data[$i] = $this_data; $i++; } } catch (\Exception $e) { return false; } return $data; }
public function _checkFile($file) { try { $handle = fopen($file, "r"); $countRow = 1; while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) { mb_convert_variables("UTF-8", "auto", $row); $this->error = ""; $targetrow = $this->_setContent($row); if ($row[0] != "room") { // バリデーションチェック関数呼び出し $this->_elementNum($row); $this->_orBlank($row); $this->_checkHyphen($row[0]); $this->_integerOverZero($row[1]); $this->_checkSessionCombi($row[0], $row[1]); $this->_checkDate($row[3]); $this->_checkTime($row[0], $row[4], $row[5], $row[3]); $this->_chairPersonOne($row[6], $row[7]); $this->_commentatorsCheck($row[8], $row[9]); array_push($this->checkResult, array('row' => $countRow, 'content' => $targetrow, 'error' => $this->error)); $countRow++; } } } catch (Exception $e) { $this->rollback(); } }
/** * ファイルの行読み込み * @return string|boolean 読み出した文字列、または読み込むデータがない場合はFALSEを返す * @access public */ public function read() { $str = fgets($this->stream); //mb_convert_variables($this->charset, "ASCII,JIS,UTF-8,EUC-JP,SJIS-win", $str); mb_convert_variables($this->charset, "ASCII,JIS,SJIS-win,UTF-8,EUC-JP", $str); return $str; }
/** * Return converted Response'body * * @param string $body * @param string|array $metadata 'content-type' * $param $remains * * @return mixed */ public final function convert($body, $metadata = array(), $remains = null) { if (is_string($metadata)) { $ctype = $metadata; } elseif (is_array($metadata)) { $ctype = isset($metadata['content-type']) ? $metadata['content-type'] : null; } else { $ctype = null; } $body = $this->_initBody($body); $encoding_from = $this->_encodingFrom($body, $ctype); // if not avilable for mbstring, using iconv if (!in_array($encoding_from, mb_list_encodings())) { $body = @iconv($encoding_from, 'UTF-8', $body); if (isset($remains)) { foreach ($remains as $k => $v) { $remains[$k] = @iconv($encoding_from, 'UTF-8', $v); } return array($body, $remains); } return $body; } if (isset($remains)) { @mb_convert_variables('UTF-8', $encoding_from, $body, $remains); return array($body, $remains); } else { $body = mb_convert_encoding($body, 'UTF-8', $encoding_from); return $body; } }
public static function exportCSV($data) { mb_convert_variables('SJIS', 'UTF-8', $data); $file = fopen('csv/data.csv', 'w'); fwrite($file, $data); fclose($file); }
public function init_flow_handle(Flow $flow) { if (Mobile::is_mobile()) { $vars = $flow->vars(); mb_convert_variables('utf-8', 'utf-8,SJIS-win', $vars); $flow->vars($vars); } }
public function ajaxautocompleteshowwords($request, $response) {/*{{{*/ $request->convertToGBK(); $words = DAL::get()->queryMedicalWords4Autocomplete('searchdict', $request->word); mb_convert_variables('utf-8','gbk', $words); echo json_encode($words); return parent::DIRECT_OUTPUT; }/*}}}*/
/** * パラメータの変換 * @return null */ private function _paramConvert() { if (sfJpMobile::isDocomo() || sfJpMobile::isKddi()) { foreach ($this->getContext()->getRequest()->getParameterHolder()->getAll() as $key => $val) { mb_convert_variables('UTF-8', 'SJIS-win,UTF-8', $val); $this->getContext()->getRequest()->setParameter($key, $val); } } }
public function ajaxGetAttachmentData($request, $response) {/*{{{*/ $attachment = DAL::get()->find('Attachment', $request->aid); $result['filename'] = $attachment->fileName; $result['atturl'] = TuClient::getInstance()->getUrl($attachment->filePath); mb_convert_variables('utf8', 'gbk', $result); echo json_encode($result); return parent::DIRECT_OUTPUT; }/*}}}*/
/** * Jsonを出力する * * @access public * @param array $encode_param 出力するJSONにエンコードする値 */ function preforward($encode_param = array()) { $client_enc = $this->ctl->getClientEncoding(); if (mb_enabled() && strcasecmp('UTF-8', $client_enc) != 0) { mb_convert_variables('UTF-8', $client_enc, $encode_param); } $encoded_param = json_encode($encode_param); $this->header(array('Content-Type' => 'application/json; charset=UTF-8')); echo $encoded_param; }
function execute(&$controller, &$xoopsUser) { $filename = sprintf('%s User data List.csv', $GLOBALS['xoopsConfig']['sitename']); $text = ''; $field_line = ''; $user_handler =& $this->_getHandler(); $criteria = new CriteriaElement(); $criteria->setSort('uid'); $users = $user_handler->getObjects($criteria); if (!$users || count($users)==0){ return USER_FRAME_VIEW_INDEX; } foreach ($users[0]->gets() as $key=>$var){ $_f = '_MD_USER_LANG_'.strtoupper($key); $field_line .= (defined($_f) ? constant($_f) : $key).","; } $field_line .= "\n"; foreach ($users as $u){ $user_data = ''; foreach ($u->gets() as $key=>$value){ switch ($key){ case 'user_regdate': case 'last_login': $value = $value ? formatTimestamp($value, 'Y/n/j H:i') : ''; break; default: } if (preg_match('/[,"\r\n]/', $value)) { $value = preg_replace('/"/', "\"\"", $value); $value = "\"$value\""; } $user_data .= $value . ','; } $text .= trim($user_data, ',')."\n"; } $text = $field_line.$text; /// japanese if (strncasecmp($GLOBALS['xoopsConfig']['language'], 'ja', 2)===0){ mb_convert_variables('SJIS', _CHARSET, $text); } if( preg_match('/firefox/i' , xoops_getenv('HTTP_USER_AGENT')) ){ header("Content-Type: application/x-csv"); }else{ header("Content-Type: application/vnd.ms-excel"); } header("Content-Disposition: attachment ; filename=\"{$filename}\"") ; exit($text); }
/** * Jsonを出力する * @access public * @param array $encode_param 出力するJSONにエンコードする値 * @see Admin_ViewClass::preforward */ function preforward($encode_param) { $client_enc = $this->ctl->getClientEncoding(); if (mb_enabled() && strcasecmp('UTF-8', $client_enc) != 0) { mb_convert_variables('UTF-8', $client_enc, $encode_param); } $this->jsonI18n($encode_param); $encoded_param = json_encode($encode_param); header('Content-Type: application/json; charset=UTF-8'); echo $encoded_param; exit; }
function initialize(&$controller) { if ($this->isMobile()) { if (isset($controller->params['url'][Configure::read('Session.cookie')])) { $this->Session->id($controller->params['url'][Configure::read('Session.cookie')]); $this->Session->renew(); } if ($controller->data) { mb_convert_variables('UTF-8', 'SJIS-win', $controller->data); } } }
/** * リソースリクエスト実行 * * リモートURLにアクセスしてRSSだったら配列に、 * そうでなかったらHTTP Body文字列をリソースとして扱います。 * * @return BEAR_Ro * @throws BEAR_Resource_Execute_Exception */ public function request() { $reqMethod = array(); $reqMethod[BEAR_Resource::METHOD_CREATE] = HTTP_Request2::METHOD_POST; $reqMethod[BEAR_Resource::METHOD_READ] = HTTP_Request2::METHOD_GET; $reqMethod[BEAR_Resource::METHOD_UPDATE] = HTTP_Request2::METHOD_PUT; $reqMethod[BEAR_Resource::METHOD_DELETE] = HTTP_Request2::METHOD_DELETE; assert(isset($reqMethod[$this->_config['method']])); try { // 引数以降省略可能 config で proxy とかも設定可能 $request = new HTTP_Request2($this->_config['uri'], $reqMethod[$this->_config['method']]); $request->setHeader("user-agent", 'BEAR/' . BEAR::VERSION); $request->setConfig("follow_redirects", true); if ($this->_config['method'] === BEAR_Resource::METHOD_CREATE || $this->_config['method'] === BEAR_Resource::METHOD_UPDATE) { foreach ($this->_config['values'] as $key => $value) { $request->addPostParameter($key, $value); } } $response = $request->send(); $code = $response->getStatus(); $headers = $response->getHeader(); if ($code == 200) { $body = $response->getBody(); } else { $info = array('code' => $code, 'headers' => $headers); throw $this->_exception($response->getBody(), $info); } } catch (HTTP_Request2_Exception $e) { throw $this->_exception($e->getMessage()); } catch (Exception $e) { throw $this->_exception($e->getMessage()); } $rss = new XML_RSS($body, 'utf-8', 'utf-8'); PEAR::setErrorHandling(PEAR_ERROR_RETURN); // @todo Panda::setPearErrorHandling(仮称)に変更しエラーを画面化しないようにする $rss->parse(); $items = $rss->getItems(); if (is_array($items) && count($items) > 0) { $body = $items; $headers = $rss->getChannelInfo(); $headers['type'] = 'rss'; } else { $headers['type'] = 'string'; $body = array($body); } // UTF-8に $encode = mb_convert_variables('UTF-8', 'auto', $body); $ro = BEAR::factory('BEAR_Ro')->setBody($body)->setHeaders($headers); /* @var $ro BEAR_Ro */ PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array('Panda', 'onPearError')); return $ro; }
function test_preforward_non_utf8() { $this->test_ctl->setClientEncoding('EUC-JP'); $param = array("a", "あいうえ"); mb_convert_variables('EUC-JP', 'UTF-8', $param); ob_start(); // stop header output for testing. @$this->view_json->preforward($param); $result = ob_get_contents(); ob_end_clean(); $this->assertEqual($result, '["a","\\u3042\\u3044\\u3046\\u3048"]'); $this->test_ctl->setClientEncoding('UTF-8'); }
function execute() { $filename = sprintf('%s_Profile_data_List.csv', $GLOBALS['xoopsConfig']['sitename']); $text = ''; $field_line = 'uid,'; $handler =& $this->_getHandler(); $defHandler =& xoops_getmodulehandler('definitions'); $defArr =& $defHandler->getDefinitions(false); $criteria = new CriteriaElement(); $criteria->setSort('uid'); $dataArr = $handler->getObjects($criteria); if (count($dataArr)==0){ return PROFILE_FRAME_VIEW_INDEX; } foreach (array_keys($defArr) as $key){ $field_line .= $var['label'].","; } $field_line .= "\n"; foreach ($dataArr as $profile){ $profile_data = ''; foreach ($profile->gets() as $key=>$value){ if($defArr[$key]->get('type')=='date'){ $value = $value ? formatTimestamp($value, 'Y/n/j H:i') : ''; } if (preg_match('/[,"\r\n]/', $value)) { $value = preg_replace('/"/', "\"\"", $value); $value = "\"$value\""; } $profile_data .= $value . ','; } $text .= trim($profile_data, ',')."\n"; } $text = $field_line.$text; /// japanese if (strncasecmp($GLOBALS['xoopsConfig']['language'], 'ja', 2)===0){ mb_convert_variables('SJIS', _CHARSET, $text); } if( preg_match('/firefox/i' , xoops_getenv('HTTP_USER_AGENT')) ){ header("Content-Type: application/x-csv"); }else{ header("Content-Type: application/vnd.ms-excel"); } header("Content-Disposition: attachment ; filename=\"{$filename}\"") ; exit($text); }
/** * @param $file_path * @return string */ public function putFile($file_path) { setlocale(LC_ALL, 'ja_JP.UTF-8'); $dir = self::$tmp_root . '/' . date('Ymd') . '/'; if (!file_exists($dir)) { @mkdir($dir, 0777); } # 一時ファイル名 $tmp_file = $dir . microtime(true) . '_tmp.csv'; # 改行の削除 $content = file_get_contents($file_path); mb_convert_variables('UTF-8', 'SJIS-win', $content); file_put_contents($tmp_file, $content); return $tmp_file; }
/** * iniファイルを読込みます。 * * @param string $configfile iniファイルのパス * @return array */ public static function readIniFile($configfile) { if (!file_exists($configfile)) { $this->log->info("Filterの設定ファイルが存在しません。({$configfile})"); return NULL; } $config = parse_ini_file($configfile, true); if (!is_array($config)) { $this->log->error("Filterの設定ファイルに誤りがあります。({$configfile})"); return NULL; } if (CONFIG_CODE != INTERNAL_CODE) { mb_convert_variables(INTERNAL_CODE, CONFIG_CODE, $config); } return $config; }
public function make($list, $fixed_options, $options) { Configure::write('debug', 0); ini_set("memory_limit", -1); set_time_limit(0); $this->_textData = ''; $options = array_merge($this->_defaultOptions, $options); extract($options); mb_convert_variables($export_encoding, $array_encoding, $list); // keyを振りなおしておく。 $list = array_merge($list); $list_count = count($list); //$listにカンマか"がいた時の対応 $return_text = ''; foreach ($list as $row => $list_val) { $column_options = $fixed_options; if (array_key_exists($row + 1, $extra_fixed_options)) { $column_options = $extra_fixed_options[$row + 1]; } elseif (array_key_exists($row - $list_count, $extra_fixed_options)) { $column_options = $extra_fixed_options[$row - $list_count]; } foreach ($column_options as $fixed_option_key => $fixed_info) { if (!array_key_exists($fixed_option_key, $list_val)) { //必要なデータが存在しないエラー throw new MethodNotAllowedException('data not exist'); } else { if (strlen($list_val[$fixed_option_key]) > $fixed_info['length']) { throw new MethodNotAllowedException('length error'); } } if ($fixed_info['type'] == 'text') { $return_text .= str_pad($list_val[$fixed_option_key], $fixed_info['length']); } elseif ($fixed_info['type'] == 'integer') { $return_text .= sprintf('%0' . $fixed_info['length'] . 's', $list_val[$fixed_option_key]); } else { throw new MethodNotAllowedException('type error'); } } $return_text .= $line_feed_code; } $this->_textData = $return_text; $save_directory = $directory . $file_name; $fp = fopen($save_directory, 'w'); fwrite($fp, $return_text); fclose($fp); return $save_directory; }
/** * 404の出力 * @see Api_ViewClass::preforward() */ function preforward($param = false) { if ($param !== false) { $this->logger->log(LOG_CRIT, $param); } // エンコードをUTF-8に変更する $client_enc = $this->ctl->getClientEncoding(); if (mb_enabled() && strcasecmp('UTF-8', $client_enc) != 0) { mb_convert_variables('UTF-8', $client_enc, $param); } $param = json_encode($param); // 出力 header("HTTP/1.1 500 Interal Server Error"); header('Content-Type: application/json; charset=UTF-8'); echo $param; exit; }
function test_preforward_non_utf8() { $controller = new Ethna_Controller_Dummy(); $form = new Ethna_ActionForm_Dummy($controller); $controller->setActionForm($form); $backend = $controller->getBackend(); $backend->setActionForm($form); $view = new Ethna_View_Json($backend, "dummy", ""); $controller->setClientEncoding('EUC-JP'); ob_start(); $param = array("a", "あいうえ"); mb_convert_variables('EUC-JP', 'UTF-8', $param); @$view->preforward($param); @$view->forward(); $content = ob_get_clean(); $this->assertEquals($content, '["a","\\u3042\\u3044\\u3046\\u3048"]'); }
/** * * @param type $types */ public function sendResponse($data, $headers = [], $statusCode = 200, $statusText = 'OK') { $di = $this->getDI(); $ext = $di['request']->getBestAccept(); $charset = $di['request']->getProducesCharset(); if ($charset != 'utf-8') { $ext .= '; charset=' . $charset; $statusText = mb_convert_encoding($statusText, $charset, 'utf-8'); mb_convert_variables($charset, 'utf-8', $data); } $this->setStatusCode($statusCode, $statusText); $handler = $di['apibird']->getResponseExtension($ext); if (empty($handler)) { $handler = $di['apibird']->getDefaultProducesExtension(); } if (is_callable($data)) { $typeName = $di['apibird']->getExtensionHandlerName($ext); if ($typeName) { $data = $data($typeName); } else { $data = $data(); } } if (is_object($data)) { $data = get_object_vars($data); } $fn = $di['apibird']->getDataHandler(); if (is_callable($fn)) { $data = $fn($data, $statusCode, $statusText); } $this->setHeader('Content-Type', $ext); if (is_array($headers)) { foreach ($headers as $key => $value) { $this->setHeader($key, $value); } } else { $this->setHeaders($headers); } if (is_scalar($data)) { $this->setContent($data); } else { $this->setContent($handler->toFormat($data)); } $this->sendHeaders()->send()->exitOnError($statusCode); }
function generate_csv($univ_id, $user_id, $year, $month, $room, $building, $teacher, $days = array()) { $start = 1; $header = "No,残留日,残留者ユーザID,場所コード,建物コード,理由,その他,申請日,申請者ユーザID,R更新者,R更新日付,R更新時刻\n"; mb_convert_variables('SJIS-win', 'UTF-8', $header); if (empty($days)) { if ($year == date('Y') && date('m') == $month) { $start = date('d'); } $days = range($start, date('t', strtotime("{$year}/{$month}/1"))); } $data = array(); foreach ($days as $d) { $date = "{$year}/{$month}/{$d}"; $data[] = implode(',', array('', $date, $univ_id, $room, $building, '1', $user_id, '', $teacher, '', '', '')); } $csv = implode("\n", $data); return $header . $csv; }
public function loadCSV($filename) { $this->begin(); try { //self::checkRelatedPoster(); $handle = fopen($filename, "r"); while (($row = fgetcsv($handle, 3000, ",")) !== FALSE) { mb_convert_variables("UTF-8", "auto", $row); $presenData = array('room' => $row[0], 'session_order' => $row[1], 'presentation_order' => $row[2], 'date' => $row[3], 'title' => $row[4], 'abstract' => $row[5], 'keyword' => $row[6], 'authors_name' => $row[7], 'authors_affiliation' => $row[8], 'event_id' => $_SESSION['event_id']); if ($row[0] != "room") { $this->create($presenData); $this->save(); } } $this->commit(); } catch (Exception $e) { $this->rollback(); } }
function utf8EncodeRecursive(&$data) { if (is_array($data) || is_object($data)) { settype($data, 'array'); foreach ($data as &$_val) { utf8EncodeRecursive($_val); } } else { $data = strip_tags(html_entity_decode($data)); if (extension_loaded('mbstring')) { global $encodings; if (!$encodings) { $encodings = array(); foreach (explode(',', 'UTF-8,ISO-8859-1,ISO-8859-2,ISO-8859-3,ISO-8859-4,ISO-8859-5,ISO-8859-6,ISO-8859-7,ISO-8859-8,ISO-8859-9,ISO-8859-10,ISO-8859-13,ISO-8859-14,ISO-8859-15,ISO-8859-16,Windows-1252,Windows-1250,Windows-1251,Windows-1254') as $encoding) { if (in_array($encoding, mb_list_encodings())) { $encodings[] = $encoding; } } mb_detect_order(array_merge($encodings, mb_list_encodings())); } if (($encoding = mb_detect_encoding($data, null, true)) != 'UTF-8') { mb_convert_variables('UTF-8', $encoding, $data); } } elseif (!preg_match('%^(?: [\\x09\\x0A\\x0D\\x20-\\x7E] # ASCII | [\\xC2-\\xDF][\\x80-\\xBF] # non-overlong 2-byte | \\xE0[\\xA0-\\xBF][\\x80-\\xBF] # excluding overlongs | [\\xE1-\\xEC\\xEE\\xEF][\\x80-\\xBF]{2} # straight 3-byte | \\xED[\\x80-\\x9F][\\x80-\\xBF] # excluding surrogates | \\xF0[\\x90-\\xBF][\\x80-\\xBF]{2} # planes 1-3 | [\\xF1-\\xF3][\\x80-\\xBF]{3} # planes 4-15 | \\xF4[\\x80-\\x8F][\\x80-\\xBF]{2} # plane 16 )*$%xs', $data)) { if (extension_loaded('iconv')) { $data = iconv(iconv_get_encoding('internal_encoding'), 'UTF-8//IGNORE', $data); } else { $data = utf8_encode($data); } } } }
function xpress_block_cache_read($mydirname, $block_name) { $xml_name = $block_name . '.xml'; $xml_data = xpress_cache_read($mydirname, $xml_name); $GLOBALS['DO_LIBXML_PATCH'] = get_xpress_mod_config($mydirname, 'libxml_patch'); // The character-code not treatable exists when 'XML_unserialize' of PHP5 processes EUC-JP. // And, the result is returned by character-code UTF-8. // Measures // After the character-code is converted into UTF-8, XML_unserialize will be processed. if (strstr($xml_data, '<?xml version="1.0" encoding="EUC-JP" ?>') !== false && version_compare(PHP_VERSION, '5.0.0', '>')) { $xml_data = str_replace('<?xml version="1.0" encoding="EUC-JP" ?>', '<?xml version="1.0" encoding="UTF-8" ?>', $xml_data); $ans = mb_convert_variables('UTF-8', 'EUC-JP', &$xml_data); //EUC-JP to UTF-8 $ret = @xpress_XML_unserialize($xml_data); $ans = mb_convert_variables('EUC-JP', 'UTF-8', &$ret); //UTF-8 to EUC-JP } else { $ret = xpress_XML_unserialize($xml_data); } return $ret; }
public function loadCSV($filename) { $this->begin(); try { $handle = fopen($filename, "r"); $roomGroup = array(); $saveRooms = array(); $roomOrder = 1; $event_id = $_SESSION['event_id']; while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) { mb_convert_variables("UTF-8", "auto", $row); $scheduleData = array('room' => $row[0], 'order' => $row[1], 'category' => $row[2], 'date' => $row[3], 'start_time' => $row[4], 'end_time' => $row[5], 'chairperson_name' => $row[6], 'chairperson_affiliation' => $row[7], 'commentator_name' => $row[8], 'commentator_affiliation' => $row[9], 'event_id' => $_SESSION['event_id']); //すでに登録しているroomでないか、一行目の説明でないか if (!in_array($row[0], $roomGroup) && $row[0] != "room") { // 予約語ALLは小文字大文字関わらずroomには登録しない、allの場合はALLに変換してsession保存 if (strtolower($row[0]) != 'all') { array_push($roomGroup, $row[0]); array_push($saveRooms, array('name' => $row[0], 'order' => $roomOrder, 'event_id' => $event_id)); $roomOrder++; } else { $scheduleData['room'] = 'ALL'; $scheduleData['order'] = 0; $scheduleData['chairperson_name'] = ""; $scheduleData['chairperson_affiliation'] = ""; $scheduleData['commentator_name'] = ""; $scheduleData['commentator_affiliation'] = ""; } } // フォーマットヘッダー無視用 if ($row[0] != "room") { $this->create($scheduleData); $this->save(); } } $this->commit(); self::_import_rooms($saveRooms); } catch (Exception $e) { $this->rollback(); } }
/** * CSVファイル読込 */ function readCsvFile() { setlocale(LC_ALL, 'ja_JP.UTF-8'); // setlocale(LC_ALL,'ja_JP.Shift_JIS'); $csv_list = array(); $csv_file = $this->setting["csv_temp_path"] . $this->setting["csv_temp_file"]; if (!file_exists($csv_file)) { return $csv_list; } $text = file_get_contents($csv_file); $temp = tmpfile(); fwrite($temp, $text); rewind($temp); $line_num = 0; while (($data = fgetcsv($temp, 0, ",")) !== FALSE) { if ($line_num > 0) { //追加分 mb_convert_variables('utf8', 'sjis-win', $data); for ($i = 0; $i < count($data); $i++) { if (strpos($data[$i], ",") !== false) { $text = $data[$i]; $text = str_replace('"', '', $text); $text = explode(",", $text); array_splice($data, $i, 1, array($text[0], $text[1])); break; } } foreach ($this->setting["csv"] as $key => $col) { if (isset($data[$key])) { // $line["edit_" . $col] = mb_convert_encoding($data[$key], 'utf8', 'sjis-win'); $line["edit_" . $col] = $data[$key]; } } $csv_list[] = $line; } $line_num++; } fclose($temp); return $csv_list; }
/** * CsvStreamedResponse constructor. * * @param string $filename * @param int $status * @param array $headers */ public function __construct($filename = null, $status = 200, $headers = array()) { parent::__construct(null, $status, $headers); $this->headers->set('Content-Type', 'text/csv; charset=utf-8'); $this->headers->set('Content-Disposition', 'attachment; filename="' . ($filename ?: 'file') . '.csv"'); $this->callback = function () { $handle = fopen('php://output', 'w'); // пишем шапку if (isset($this->encoding) && 'UTF-8' !== strtoupper($this->encoding)) { mb_convert_variables($this->encoding, 'UTF-8', $this->colums); } fputcsv($handle, $this->colums, $this->delimiter, $this->enclosure); $fields = array_keys($this->colums); if ($this->iterator instanceof IterableResult) { // для каждой строки foreach ($this->iterator as $row) { $dataRow = array_shift($row); // если задан колбэк для обработки одной строки if (isset($this->dataRowCallback)) { $callback = $this->dataRowCallback; $callback($dataRow); } // раскидываем по колонкам данные $fileRow = array(); foreach ($fields as $field) { $fileRow[] = isset($dataRow[$field]) ? $dataRow[$field] : $this->emptyCellValue; } if (isset($this->encoding) && 'UTF-8' !== strtoupper($this->encoding)) { mb_convert_variables($this->encoding, 'UTF-8', $fileRow); } fputcsv($handle, $fileRow, $this->delimiter, $this->enclosure); } } else { throw new \RuntimeException('Unknown iterator. Set a different callback.'); } fclose($handle); }; }