diff options
author | Ignace Nyamagana Butera <nyamsprod@gmail.com> | 2014-04-22 14:43:11 +0200 |
---|---|---|
committer | Ignace Nyamagana Butera <nyamsprod@gmail.com> | 2014-04-22 16:18:23 +0200 |
commit | bea1bd36976aaa6db5d94967424748758f3ea484 (patch) | |
tree | c68cedc875a7817b9ec1996d23c61deecbb27585 /examples | |
parent | 955236dbb6538f0b91eaf4cb0b62a1e52120434d (diff) | |
download | csv-bea1bd36976aaa6db5d94967424748758f3ea484.zip csv-bea1bd36976aaa6db5d94967424748758f3ea484.tar.gz csv-bea1bd36976aaa6db5d94967424748758f3ea484.tar.bz2 |
adding stream filter trait
Diffstat (limited to 'examples')
-rw-r--r-- | examples/lib/FilterTranscode.php | 56 | ||||
-rw-r--r-- | examples/stream.php | 17 |
2 files changed, 73 insertions, 0 deletions
diff --git a/examples/lib/FilterTranscode.php b/examples/lib/FilterTranscode.php new file mode 100644 index 0000000..30cf1ca --- /dev/null +++ b/examples/lib/FilterTranscode.php @@ -0,0 +1,56 @@ +<?php + +namespace lib; + +class FilterTranscode extends php_user_filter +{ + private static $name = 'convert.transcode.'; + + private $encoding_from = 'auto'; + + private $encoding_to; + + public function onCreate() + { + if (strpos($this->filtername, self::$name) !== 0) { + return false; + } + + $params = substr($this->filtername, strlen(self::$name)); + if (! preg_match('/^([-\w]+)(:([-\w]+))?$/', $params, $matches)) { + return false; + } + + if (isset($matches[1])) { + $this->encoding_from = $matches[1]; + } + + $this->encoding_to = mb_internal_encoding(); + if (isset($matches[3])) { + $this->encoding_to = $matches[3]; + } + + $this->params['locale'] = setlocale(LC_CTYPE, '0'); + if (stripos($this->params['locale'], 'UTF-8') === false) { + setlocale(LC_CTYPE, 'en_US.UTF-8'); + } + + return true; + } + + public function onClose() + { + setlocale(LC_CTYPE, $this->params['locale']); + } + + public function filter($in, $out, &$consumed, $closing) + { + while ($res = stream_bucket_make_writeable($in)) { + $res->data = @mb_convert_encoding($res->data, $this->encoding_to, $this->encoding_from); + $consumed += $res->datalen; + stream_bucket_append($out, $res); + } + + return PSFS_PASS_ON; + } +} diff --git a/examples/stream.php b/examples/stream.php new file mode 100644 index 0000000..927e22e --- /dev/null +++ b/examples/stream.php @@ -0,0 +1,17 @@ +<?php + +use League\Csv\Reader; +use lib\FilterTranscode; + +require '../vendor/autoload.php'; +require 'lib/FilterTranscode.php'; + +stream_filter_register(FilterTranscode::$name."*", "FilterTranscode"); + +$reader = new Reader('path/to/chinese/file.csv'); +$reader->appendStreamFilter(FilterTranscode::$name."big5:utf8"); +$reader->setOffset(1); +$reader->setLimit(10); +$res = $reader->fetchAll(); + +print_r($res); //the data is transcoded by the Stream Filter from BIG5 to UTF-8 |