巨大ãªSJISã®CSVãã¡ã¤ã«ãfgetcsvé¢æ°ã§å¦çãã
ãã¦ãååè¨äºãPHPでメモリ上に一時ファイルを作るãã§ã¯ãfile_get_contentsé¢æ°ã§CSVãã¡ã¤ã«å ¨ä½ãåå¾ãã¦æåã¨ã³ã³ã¼ãã£ã³ã°ã®å¤æãè¡ããå¤æçµæã«å¯¾ãã¦fgetcsvé¢æ°ãå©ç¨ãã¾ãããããããCSVãã¡ã¤ã«ã巨大ãªå ´åã«ã¯file_get_contentsã使ãã¨ã¡ã¢ãªä¸éã«å¼ã£ããã£ã¦PHPãåæ¢ãã¦ãã¾ãã¾ãã
ãã¡ãããUTF-8ã®CSVãã¡ã¤ã«ã«å¯¾ãã¦fgetcsvãå©ç¨ããã®ã§ããã°ãã©ããªå¤§ããªCSVãã¡ã¤ã«ã ããã¨å¦çãããã¨ãå¯è½ã§ãããªããªããfgetcsvã¯ãã¡ã¤ã«ã1è¡åä½ã§èªã¿è¾¼ãé¢æ°ã§ãããã1è¡åã®ã¡ã¢ãªæ¶è²»ã ãã§ãã¡ã¤ã«å ¨ä½ãèªã¿è¾¼ã¿ç¶ããããããã§ãï¼æ£ç¢ºã«ã¯ã¹ããªã¼ã ä¸ã®ãã¼ã¿ã¯ãããã¡ãªã³ã°ãããã®ã§ããããã¡ãµã¤ãºåã®ã¡ã¢ãªã¯æ¶è²»ãã¾ããï¼ã
ããã§ã¯ã巨大ãªSJISã®CSVãã¡ã¤ã«ãfgetcsvã§å¦çãããå ´åã¯ã©ãããã°è¯ãã®ã§ããããããã®ãããªå ´åã«ã¯ãã¹ããªã¼ã ãã£ã«ã¿ã便å©ã§ããã¹ããªã¼ã ãã£ã«ã¿ã¨ããã®ã¯ãã¹ããªã¼ã ä¸ã«æµããæååãå å·¥ããããã®ä»çµã¿ã§ããä»åãStream_Filter_Mbstringã¨ãããæåã¨ã³ã³ã¼ãã£ã³ã°å¤æãè¡ãã¹ããªã¼ã ãã£ã«ã¿ãä½ã£ã¦ã¿ã¾ããã
åååæ§ãSJISã®CSVãã¡ã¤ã«ãå¦çããã³ã¼ãä¾ã示ãã¾ãã
<?php require_once 'Stream/Filter/Mbstring.php'; $ret = stream_filter_register("convert.mbstring.*", "Stream_Filter_Mbstring"); $fp = fopen("example.csv", 'r'); $filter_name = 'convert.mbstring.encoding.SJIS-win:UTF-8'; $filter = stream_filter_append($fp, $filter_name, STREAM_FILTER_READ); $current_locale = setlocale(LC_ALL, '0'); // ç¾å¨ã®ãã±ã¼ã«ãåå¾ setlocale(LC_ALL, 'ja_JP.UTF-8'); while ($values = fgetcsv($fp, 10000)) { print_r($values); } setlocale(LC_ALL, $current_locale); // ãã±ã¼ã«ãæ»ã fclose($fp);
ãã®ããã«ãfopenã§ä½æããã¹ããªã¼ã ã«stream_filter_appendããã ãã§ã¹ããªã¼ã ãã£ã«ã¿ãé©ç¨ã§ãã¾ããããã§å®éã«æ°ç¾MBããCSVãæå¾ã¾ã§èªããã¨ãã§ãã¾ãã
ãã¡ãããå®æ¡ä»¶ã§ã¯ããå°ãã¨ã©ã¼å¦çãçé¢ç®ã«ããã¹ãã§ããã¾ããååè¨äºã®ã³ã¡ã³ãã§id:moriyoshiããããããã³ããå ¥ã£ã¦ãã¾ããããfgetcsvã®ç¬¬2å¼æ°ã«ã注æãå¿ è¦ã§ããæ¬å½ã«10000ãã¤ããè¶ ããè¡ãæ¥ãªãã®ãã©ããã巨大ãªè¡ããã£ãå ´åã«ã¨ã©ã¼ãåºãä»çµã¿ãããã®ãããªã©ã¯æ³¨æãå¿ è¦ãªç¹ã§ããã
ãã®Stream_Filter_Mbstringã¯pearã§ç°¡åã«ã¤ã³ã¹ãã¼ã«ã§ãã¾ãã
$ sudo pear channel-discover openpear.org $ sudo pear install openpear/Stream_Filter_Mbstring
å®ã¯ä¼¼ãç®çã®convert.iconv.*ã¨ãããã£ã«ã¿ãPHPããã©ã«ãã§å©ç¨ã§ãã¾ããããããå®æ¡ä»¶ã«å©ç¨ããã®ã¯å³ããã¨æãã¾ããã¨ããã®ããä¸æ£ãªæåã1ãã¤ãã§ãå«ã¾ãã¦ããã¨ãã¹ããªã¼ã å
¨ä½ã0ãã¤ãã«å¤æãã¦ãã¾ãã®ã§ãï¼ä½ããã¾ãåé¿æ¹æ³ãããã®ããããã¾ãããï¼ãã§ãã®ã§ãStream_Filter_Mbstringãèªä½ããããã§ãã
ä»ã«ã©ããªãã£ã«ã¿ãåå¨ãããã¯ãPHP: 利用できるフィルタのリスト - Manualããåç §ãã¦ãã ããã
æå¾ã«ãä»åStream_Filter_Mbstringãç½®ããã¦ããã£ã¦ããopenpearã¯ç´ æ´ãããã§ãããããã«ã¤ãã¦ã¯å¥è¨äºã«ã¾ã¨ãããã¨æãã¾ãã