有没有人有使用PHP阅读WebVTT(.vtt)文件的经验?
我正在CakePHP中开发一个应用程序,我需要阅读一堆vtt文件并获取开始时间和相关文本。
以文件为例:
00:00.999 --> 00:04.999 sentence one 00:04.999 --> 00:07.999 sentence two 00:07.999 --> 00:10.999 third sentence with a line break 00:10.999 --> 00:14.999 a fourth sentence on three lines
我需要能够提取这样的东西:
00:00.999 sentence one 00:04.999 sentence two 00:07.999 third sentence with a line break 00:10.999 a fourth sentence on three lines
请注意,可以有换行符,因此每个时间戳之间没有固定的行数。
我的计划是搜索" - >"这是每个时间戳之间的公共字符串。有没有人有任何想法如何最好地实现这一目标?
答案 0 :(得分:1)
这似乎达到了我的需要,即输出开始时间和任何后续文本行。我正在使用的文件相当小,所以使用PHP的file()函数将所有内容读入数组似乎没问题;不知道这对大文件有效。
$file = 'test.vtt';
$file_as_array = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($file_as_array as $f) {
// Find lines containing "-->"
$start_time = false;
if (preg_match("/^(\d{2}:[\d\.]+) --> \d{2}:[\d\.]+$/", $f, $match)) {
$start_time = explode('-->', $f);
$start_time = $start_time[0];
echo '<br>';
echo $start_time;
}
// It's a line of the file that doesn't include a timestamp, so it's caption text. Ignore header of file which includes the word 'WEBVTT'
if (!$start_time && (!strpos($f, 'WEBVTT')) ) {
echo ' ' . $f . ' ';
}
}
}
答案 1 :(得分:0)
您可以这样做:
<?PHP
function send_reformatted($vtt_file){
// Add these headers to ease saving the output as text file
header("Content-type: text/plain");
header('Content-Disposition: inline; filename="'.$vtt_file.'.txt"');
$f = fopen($vtt_file, "r");
$line_new = "";
while($line = fgets($f)){
if (preg_match("/^(\d{2}:[\d\.]+) --> \d{2}:[\d\.]+$/", $line, $match)) {
if($line_new) echo $line_new."\n";
$line_new = $match[1];
} else{
$line = trim($line);
if($line) $line_new .= " $line";
}
}
echo $line_new."\n";
fclose($f);
}
send_reformatted("test.vtt");
?>
答案 2 :(得分:0)
要解析文件,您可以使用以下库:
$subtitles = Subtitles::load('subtitles.vtt');
$blocks = $subtitles->getInternalFormat(); // array
foreach ($blocks as $block) {
echo $block['start'];
echo $block['end'];
foreach ($block['lines'] as $line) {
echo $line;
}
}