Overview

Namespaces

  • Kotchasan
    • Cache
    • Database
    • Http
    • Log
    • Orm
  • None
  • PHP
  • Psr
    • Cache
    • Http
      • Message
    • Log

Classes

  • ArrayIterator
  • DateInterval
  • DOMNode
  • Kotchasan
  • Kotchasan\Accordion
  • Kotchasan\ApiController
  • Kotchasan\ArrayTool
  • Kotchasan\Cache\ApcCache
  • Kotchasan\Cache\Cache
  • Kotchasan\Cache\CacheItem
  • Kotchasan\Cache\FileCache
  • Kotchasan\CKEditor
  • Kotchasan\Collection
  • Kotchasan\Config
  • Kotchasan\Controller
  • Kotchasan\Country
  • Kotchasan\Csv
  • Kotchasan\Curl
  • Kotchasan\Currency
  • Kotchasan\Database
  • Kotchasan\Database\Db
  • Kotchasan\Database\DbCache
  • Kotchasan\Database\Driver
  • Kotchasan\Database\PdoMysqlDriver
  • Kotchasan\Database\Query
  • Kotchasan\Database\QueryBuilder
  • Kotchasan\Database\Schema
  • Kotchasan\Database\Sql
  • Kotchasan\DataTable
  • Kotchasan\Date
  • Kotchasan\DOMNode
  • Kotchasan\DOMParser
  • Kotchasan\Email
  • Kotchasan\File
  • Kotchasan\Files
  • Kotchasan\Form
  • Kotchasan\Grid
  • Kotchasan\Html
  • Kotchasan\Htmldoc
  • Kotchasan\HtmlTable
  • Kotchasan\Http\AbstractMessage
  • Kotchasan\Http\AbstractRequest
  • Kotchasan\Http\Message
  • Kotchasan\Http\NotFound
  • Kotchasan\Http\Request
  • Kotchasan\Http\Response
  • Kotchasan\Http\Stream
  • Kotchasan\Http\UploadedFile
  • Kotchasan\Http\Uri
  • Kotchasan\Image
  • Kotchasan\InputItem
  • Kotchasan\Inputs
  • Kotchasan\KBase
  • Kotchasan\Language
  • Kotchasan\ListItem
  • Kotchasan\Log\AbstractLogger
  • Kotchasan\Log\Logger
  • Kotchasan\Login
  • Kotchasan\Menu
  • Kotchasan\Mime
  • Kotchasan\Model
  • Kotchasan\Number
  • Kotchasan\ObjectTool
  • Kotchasan\Orm\Field
  • Kotchasan\Orm\Recordset
  • Kotchasan\Password
  • Kotchasan\Pdf
  • Kotchasan\Province
  • Kotchasan\Router
  • Kotchasan\Session
  • Kotchasan\Singleton
  • Kotchasan\Tab
  • Kotchasan\TableRow
  • Kotchasan\Template
  • Kotchasan\Text
  • Kotchasan\Validator
  • Kotchasan\View
  • PHPMailer
  • Psr\Log\AbstractLogger
  • Psr\Log\LogLevel
  • Psr\Log\NullLogger
  • SMTP

Interfaces

  • ArrayAccess
  • Countable
  • DateTimeInterface
  • Iterator
  • IteratorAggregate
  • Psr\Cache\CacheItemInterface
  • Psr\Cache\CacheItemPoolInterface
  • Psr\Http\Message\MessageInterface
  • Psr\Http\Message\RequestInterface
  • Psr\Http\Message\ResponseInterface
  • Psr\Http\Message\ServerRequestInterface
  • Psr\Http\Message\StreamInterface
  • Psr\Http\Message\UploadedFileInterface
  • Psr\Http\Message\UriInterface
  • Psr\Log\LoggerAwareInterface
  • Psr\Log\LoggerInterface
  • SeekableIterator
  • Serializable
  • Traversable

Traits

  • Psr\Log\LoggerTrait

Exceptions

  • Exception
  • InvalidArgumentException
  • Kotchasan\ApiException
  • Kotchasan\Cache\Exception
  • Kotchasan\Database\Exception
  • Kotchasan\InputItemException
  • LogicException
  • phpmailerException
  • RuntimeException

Functions

  • createClass
  • debug
  • getClassPath
  • Overview
  • Namespace
  • Class
  • Tree
  1: <?php
  2: /**
  3:  * @filesource Kotchasan/Csv.php
  4:  *
  5:  * @copyright 2016 Goragod.com
  6:  * @license http://www.kotchasan.com/license/
  7:  *
  8:  * @see http://www.kotchasan.com/
  9:  */
 10: 
 11: namespace Kotchasan;
 12: 
 13: /**
 14:  * CSV function.
 15:  *
 16:  * @author Goragod Wiriya <admin@goragod.com>
 17:  *
 18:  * @since 1.0
 19:  */
 20: class Csv
 21: {
 22:     /**
 23:      * @var mixed
 24:      */
 25:     private $charset;
 26:     /**
 27:      * @var mixed
 28:      */
 29:     private $columns;
 30:     /**
 31:      * @var mixed
 32:      */
 33:     private $datas;
 34:     /**
 35:      * @var mixed
 36:      */
 37:     private $keys;
 38: 
 39:     /**
 40:      * ฟังก์ชั่นนำเข้าข้อมูล CSV
 41:      * คืนค่าข้อมูลที่อ่านได้เป็นแอเรย์
 42:      *
 43:      * @param string $csv     ชื่อไฟล์รวมพาธ
 44:      * @param array  $columns ข้อมูลคอลัมน์ array('column1' => 'data type', 'column2' => 'data type', ....)
 45:      * @param array  $keys    ชื่อคอลัมน์สำหรับตรวจข้อมูลซ้ำ null(default) หมายถึงไม่ตรวจสอบ
 46:      * @param string $charset รหัสภาษาของไฟล์ ค่าเริ่มต้นคือ Windows-874 (ภาษาไทย)
 47:      *
 48:      * @return array
 49:      */
 50:     public static function import($csv, $columns, $keys = null, $charset = 'Windows-874')
 51:     {
 52:         $obj = new static();
 53:         $obj->columns = $columns;
 54:         $obj->datas = array();
 55:         $obj->charset = strtoupper($charset);
 56:         $obj->keys = $keys;
 57:         $obj->read($csv, array($obj, 'importDatas'), array_keys($columns));
 58:         return $obj->datas;
 59:     }
 60: 
 61:     /**
 62:      * อ่านไฟล์ CSV ทีละแถวส่งไปยังฟังก์ชั่น $onRow
 63:      * แถวแรกของข้อมูลคือ Header ต้องระบุเสมอ
 64:      *
 65:      * @param string   $file  ชื่อไฟล์รวมพาธ
 66:      * @param function $onRow ฟังก์ชั่นรับค่าแต่ละแถว function($data){}
 67:      * @param array $headers แอเรย์เก็บชื่อคอลัมน์สำหรับการทดสอบความถูกต้อง ถ้าไม่ระบุจะไม่ตรวจสอบ
 68:      *
 69:      * @throws Exception ถ้า Header ของไฟล์ CSV ไม่ถูกต้อง
 70:      */
 71:     public static function read($file, $onRow, $headers = array())
 72:     {
 73:         $columns = array();
 74:         $f = @fopen($file, 'r');
 75:         if ($f) {
 76:             while (($data = fgetcsv($f)) !== false) {
 77:                 if (empty($columns)) {
 78:                     if (is_array($headers)) {
 79:                         if (count($headers) != count($data)) {
 80:                             throw new \Exception('Invalid CSV Header');
 81:                         } else {
 82:                             // remove BOM
 83:                             $data[0] = self::removeBomUtf8($data[0]);
 84:                             // ตรวจสอบ Header
 85:                             foreach ($headers as $k) {
 86:                                 if (!in_array($k, $data)) {
 87:                                     throw new \Exception('Invalid CSV Header');
 88:                                 }
 89:                             }
 90:                         }
 91:                     }
 92:                     $columns = $data;
 93:                 } else {
 94:                     $items = array();
 95:                     foreach ($data as $k => $v) {
 96:                         if (isset($columns[$k])) {
 97:                             $items[$columns[$k]] = $v;
 98:                         }
 99:                     }
100:                     call_user_func($onRow, $items);
101:                 }
102:             }
103:             fclose($f);
104:         }
105:     }
106: 
107:     /**
108:      * สร้างไฟล์ CSV สำหรับดาวน์โหลด
109:      * คืนค่า true
110:      *
111:      * @param string $file    ชื่อไฟล์ ไม่ต้องมีนามสกุล
112:      * @param array  $header  ส่วนหัวของข้อมูล
113:      * @param array  $datas   ข้อมูล
114:      * @param string $charset ภาษาของ CSV ค่าเริ่มต้นคือ Windows-874 (ภาษาไทย)
115:      *
116:      * @return bool
117:      */
118:     public static function send($file, $header, $datas, $charset = 'Windows-874')
119:     {
120:         // header
121:         header('Content-Type: text/csv;charset="'.$charset.'"');
122:         header('Content-Disposition: attachment;filename="'.$file.'.csv"');
123:         // create stream
124:         $f = fopen('php://output', 'w');
125:         // charset
126:         $charset = strtoupper($charset);
127:         // csv header
128:         if (!empty($header)) {
129:             fputcsv($f, self::convert($header, $charset));
130:         }
131:         // content
132:         foreach ($datas as $item) {
133:             fputcsv($f, self::convert($item, $charset));
134:         }
135:         // close
136:         fclose($f);
137:         // คืนค่า สำเร็จ
138:         return true;
139:     }
140: 
141:     /**
142:      * remove BOM
143:      *
144:      * @param $s
145:      *
146:      * @return string
147:      */
148:     private static function removeBomUtf8($s)
149:     {
150:         if (substr($s, 0, 3) == chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF'))) {
151:             return substr($s, 3);
152:         } else {
153:             return $s;
154:         }
155:     }
156: 
157:     /**
158:      * แปลงข้อมูลเป็นภาษาที่เลือก
159:      *
160:      * @param array  $datas
161:      * @param string $charset
162:      *
163:      * @return array
164:      */
165:     private static function convert($datas, $charset)
166:     {
167:         if ($charset != 'UTF-8') {
168:             foreach ($datas as $k => $v) {
169:                 if ($v != '') {
170:                     $datas[$k] = iconv('UTF-8', $charset.'//IGNORE', $v);
171:                 }
172:             }
173:         }
174:         return $datas;
175:     }
176: 
177:     /**
178:      * ฟังก์ชั่นรับค่าจากการอ่าน CSV
179:      *
180:      * @param array $data
181:      */
182:     private function importDatas($data)
183:     {
184:         $save = array();
185:         foreach ($this->columns as $key => $type) {
186:             $save[$key] = null;
187:             if (isset($data[$key])) {
188:                 if (is_array($type)) {
189:                     $save[$key] = call_user_func($type, $data[$key]);
190:                 } elseif ($type == 'int') {
191:                     $save[$key] = (int) $data[$key];
192:                 } elseif ($type == 'double') {
193:                     $save[$key] = (float) $data[$key];
194:                 } elseif ($type == 'float') {
195:                     $save[$key] = (float) $data[$key];
196:                 } elseif ($type == 'number') {
197:                     $save[$key] = preg_replace('/[^0-9]+/', '', $data[$key]);
198:                 } elseif ($type == 'en') {
199:                     $save[$key] = preg_replace('/[^a-zA-Z0-9]+/', '', $data[$key]);
200:                 } elseif ($type == 'date') {
201:                     if (preg_match('/^([0-9]{4,4})[\-\/]([0-9]{1,2})[\-\/]([0-9]{1,2})$/', $data[$key], $match)) {
202:                         $save[$key] = "$match[1]-$match[2]-$match[3]";
203:                     } elseif (preg_match('/^([0-9]{1,2})[\-\/]([0-9]{1,2})[\-\/]([0-9]{4,4})$/', $data[$key], $match)) {
204:                         $save[$key] = "$match[3]-$match[2]-$match[1]";
205:                     }
206:                 } elseif ($type == 'datetime') {
207:                     if (preg_match('/^([0-9]{4,4})[\-\/]([0-9]{2,2})[\-\/]([0-9]{2,2})\s([0-9]{2,2}):([0-9]{2,2}):([0-9]{2,2})$/', $data[$key])) {
208:                         $save[$key] = $data[$key];
209:                     } elseif (preg_match('/^([0-9]{2,2})[\-\/]([0-9]{2,2})[\-\/]([0-9]{4,4})\s(([0-9]{2,2}):([0-9]{2,2}):([0-9]{2,2}))$/', $data[$key], $match)) {
210:                         $save[$key] = "$match[4]-$match[3]-$match[2] $match[1]";
211:                     }
212:                 } elseif ($type == 'time') {
213:                     if (preg_match('/^([0-9]{2,2}):([0-9]{2,2}):([0-9]{2,2})$/', $data[$key])) {
214:                         $save[$key] = $data[$key];
215:                     }
216:                 } elseif ($this->charset == 'UTF-8') {
217:                     $save[$key] = \Kotchasan\Text::topic($data[$key]);
218:                 } else {
219:                     $save[$key] = iconv($this->charset, 'UTF-8', \Kotchasan\Text::topic($data[$key]));
220:                 }
221:             }
222:         }
223:         if (empty($this->keys)) {
224:             $this->datas[] = $save;
225:         } else {
226:             $keys = '';
227:             foreach ($this->keys as $item) {
228:                 if ($save[$item] !== null && $save[$item] !== '') {
229:                     $keys .= $save[$item];
230:                 } else {
231:                     $save = null;
232:                     continue;
233:                 }
234:             }
235:             if (!empty($save) && !isset($this->datas[$keys])) {
236:                 $this->datas[$keys] = $save;
237:             }
238:         }
239:     }
240: }
241: 
Kotchasan API documentation generated by ApiGen