PHP code example of gyselroth / stream-iterator

1. Go to this page and download the library: Download gyselroth/stream-iterator library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

gyselroth / stream-iterator example snippets


$my_iterator = new \ArrayIterator([0,1,2,3,4,5]);
$stream = new \StreamIterator\StreamIterator($my_iterator);
$contents = $stream->getContents();
echo $contents; //Prints 012345

$my_iterator = new \ArrayIterator([0,1,2,3,4,5]);
$stream = new \StreamIterator\StreamIterator($my_iterator, function($item) {
    return '-'.$item;
})

$contents = $stream->getContents();
echo $contents; //Prints -0-1-2-3-4-5

$my_iterator = new \ArrayIterator([['foo' => 'bar'], ['foo' => 'bar']]);
$stream = new \StreamIterator\StreamIterator($my_iterator, function($item) {
    if($this->tell() === 0) {
        $string = '[';
    } else {
        $string = ',';
    }

    $string .= json_encode($item);

    if($this->eof()) {
        $string .= ']';
    }

    return $string;
})

$contents = $stream->getContents();
echo $contents; //Prints [{"foo":"bar"},{"foo":"bar"}]

$my_iterator = new \ArrayIterator([['foo' => 'bar'], ['foo' => 'bar']]);
$stream = new \StreamIterator\StreamIterator($my_iterator, function($item) {
    if($this->tell() === 0) {
        $string = '[';
    } else {
        $string = ',';
    }

    $string .= json_encode($item);

    if($this->eof()) {
        $string .= ']';
    }

    echo $string;
    flush();
    return '';
})

$contents = $stream->getContents(); //Prints [{"foo":"bar"},{"foo":"bar"}]
echo $contents; //Prints "" (Empty string)