From 24b07d6b13247523d4cf657242284d82c3f7fb49 Mon Sep 17 00:00:00 2001 From: lpotherat Date: Thu, 27 Feb 2014 16:37:44 +0100 Subject: [PATCH] Allow the class to directly stream to browser Allow the class to directly stream to browser without stream. Useful to write large json data to browser on low memory conditions. --- src/JsonStream/Encoder.php | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/JsonStream/Encoder.php b/src/JsonStream/Encoder.php index d8f6862..e98db01 100644 --- a/src/JsonStream/Encoder.php +++ b/src/JsonStream/Encoder.php @@ -5,18 +5,21 @@ class Encoder { private $_stream; + private $_echo; /** * @param resource $stream A stream resource. * @throws \InvalidArgumentException If $stream is not a stream resource. */ - public function __construct($stream) + public function __construct($stream,$echo=false) { - if (!is_resource($stream) || get_resource_type($stream) != 'stream') { + $this->_echo=$echo; + if (!$this->_echo && (!is_resource($stream) || get_resource_type($stream) != 'stream')) { throw new \InvalidArgumentException("Resource is not a stream"); } - $this->_stream = $stream; + if(!$this->_echo) + $this->_stream = $stream; } /** @@ -63,7 +66,11 @@ public function encode($value) */ private function _writeValue($value) { - fwrite($this->_stream, $value); + if(!$this->_echo){ + fwrite($this->_stream, $value); + } else { + echo $value; + } } /**