Streaming string in PHP

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading...

RFC 2397 (Section 3) states that passes data should be either in base64 encoding or urlencoded.

  • First line is a header by default
  • Empty/blank lines are ignored
function read_line( $data, $header = [], $delimiter = "\t", $skipped = 0, $counter = PHP_INT_SIZE ) {

  $fo = new SplFileObject('data://text/plain,' . urlencode($data), 'r');
  $header = empty($header) ? $fo->fgetcsv($delimiter) : $header;

  if( $skipped > 0 ) { $fo->seek ($skipped - 1); }
  
  while ( !$fo->eof() && $counter-- ) {
    $data = $fo->fgetcsv($delimiter);
    if(empty(array_filter($data, "trim"))) continue;
    yield  array_combine($header, $data);
  }  
}

Sources:

Yandex.Metrica