Skip to content

Instantly share code, notes, and snippets.

@illifw
Last active January 28, 2024 22:06
Show Gist options
  • Save illifw/de5d74e3b5d72ae46be67dc1bb90d96a to your computer and use it in GitHub Desktop.
Save illifw/de5d74e3b5d72ae46be67dc1bb90d96a to your computer and use it in GitHub Desktop.
<?php
class TSV
{
static function lines(string $file, callable $filter)
{
$handle = null;
try
{
if(false === ($handle = fopen($file, 'r')))
return false;
$headers = null;
$line = 0;
while(false === feof($handle)
&& false !== ($data = fgets($handle))
)
{
if(null === $headers
&& 0x00 === $line)
{
$headers = $data;
continue;
}
$line++;
if([null] === $data)
{
continue;
}
$res = call_user_func_array(
$filter,
[
$data,
$headers,
&$handle,
$line
]
);
if(false === $res)
continue;
yield $res;
}
fclose($handle);
$handle = null;
}
catch(Exception $e)
{
trigger_error(__METHOD__.': '.$e->getMessage(), E_USER_NOTICE);
}
finally
{
if(null !== $handle)
fclose($handle);
return false;
}
return true;
}
}
foreach(TSV::lines('H:\title.basics.tsv', function($data, $headers, $line, &$handle)
{
if($data[0] === 'tt0000002'
|| $data[0] === 'tt0000003'
|| $data[0] === 'tt1000000'
)
{
var_dump($line);
return (object) array_combine(
str_getcsv($headers, "\t"),
str_getcsv($data, "\t")
);
}
else return false;
}) as $data)
{
var_dump($data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment