ãblog.plastik.jp » PHP5 の fgetcsv() で読み込み内容が腐る現象ãã¨ããè¨äºãèªã¿ã¾ãããfgetcsv()ã ã¨SJISã®CSVãã¡ã¤ã«ããã¾ãèªããªãã®ã§ãUTF-8ã«ç´ãã¦ãã³ãã©ãªãã¡ã¤ã«ã«ä¿åãã¦fgetcsvã§èªã¿è¾¼ããã¨ããçæ¸ãã®ããã§ãã
ã¡ããã¨tmpfile()ã使ã£ã¦ããããã¦ãã¤ã¹ãªã³ã¼ãã ã¨æãã¾ããã§ããããä¸è¦ã«ãªããã¼ã¿ããã£ã¹ã¯ã«æ¸ãè¾¼ãã®ã¯ã¤ãã¤ããããªãã§ãããããããã¯ã¡ã¢ãªã«æ¸ããæ¹ãã«ãã³ããã¨æããã§ããåãªãä¸è¨ã®ããã«ãã¾ãã
<?php $data = file_get_contents("example.csv"); $data = mb_convert_encoding($data, "UTF-8", "Shift_JIS"); $fp = fopen('php://memory', 'r+'); fwrite($fp, $data); rewind($fp); // å ã»ã©æ¸ãè¾¼ãã ãã¼ã¿ãèªã¿è¾¼ã¿ã¾ãã $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);
php://memoryã¨ããã®ããã¡ã¢ãªä¸ã«ä½ãããã¡ã¤ã«ã®ãããªãã®ã§ãã詳ããã¯ãPHP: PHP 入出力ストリーム - Manualããåç
§ãã¦ãã ããã
PHPã®ã¹ããªã¼ã ã¨ããã®ã¯ããã¡ã¤ã«ã®ã¿ãªãããã·ã¼ã±ã³ã·ã£ã«ã«èªã¿æ¸ãå¯è½ãªãªã½ã¼ã¹ï¼URLãæ¨æºå ¥åºåãã½ã±ãããªã©ï¼ãçµ±ä¸çã«æ±ãããã®æ¦å¿µã§ããPHP4.3.0ããåå¨ããã®ã§ããããã¾ã使ã£ã¦ãã人ãè¦ãªãæ©è½ã§ããã
php://tempã ã¨ãµã¤ãºãä¸å®ä»¥ä¸ã®ã¨ãã ããã£ã¹ã¯ã«æ¸ããããã®ã§ããã£ã¡ã®æ¹ãã«ãã³ããããããã¾ãããä¸ã®ä¾ã¯ã¡ã¢ãªæ¶è²»éãæ°ã«ãªããªãç¶æ³ãä»®å®ãã¦ããã¨èãã¦ãã ããã
php://memoryã¯PHP5.1.0ãã使ãããã¨ããã¥ã¢ã«ã«ã¯æ¸ãã¦ããã¾ãããåã確èªããç¯å²ã§ã¯PHP 5.1.4ããæ£å¸¸ã«åä½ããããã§ãã