Yii2 — HTML Streaming


PHP
<?php 

declare( strict_types=1 );

namespace app\controllers;

// имеем некий контроллер

class ExampleController extends extends \yii\web\Controller {


/**
* Пример вывода потока данных
*/
public function actionStream() {
		// отключение буферизации
		@ob_end_clean();
		ini_set( 'output_buffering', 0 );
		// Пример потокового ответа
		$this->response->format = Response::FORMAT_RAW;
		$this->response->headers->set( 'Content-Type', 'text/plain; charset=utf-8' );
		$this->response->headers->set( "Cache-Control", "no-cache, must-revalidate" );
		$this->response->headers->set( 'Connection', 'keep-alive' );
		$this->response->headers->set( 'X-Accel-Buffering', 'no' );

		// Генератор для потоковой отдачи данных
		$generator = function () {
			for ( $i = 1; $i <= 100; $i ++ ) {
				yield "Chunk #{$i}: " . date( 'Y-m-d H:i:s' ) . "\n";
				// Небольшая задержка для имитации длительной операции
				usleep( 50000 ); // 50ms
			}
		};
		$this->response->stream = $generator;

		return $this->response;
	}