【发布时间】:2015-02-01 18:47:28
【问题描述】:
我正在寻找一种在长轮询时使用 file_get_contents 从 .txt 文件中读取 last 的有效方法。我尝试使用下面注释的代码来解决解决方案,但它破坏了长轮询 - 在显示 .txt 文件的全部内容时效果很好。
我也查看了 file_get_contents 的 offset 参数,但我不知道如何在我的代码中对其进行良好(或正常运行)的调整。我想这将涉及首先计算所述 .txt 文件中的所有单词(其本身是动态的),然后以某种方式将该单词数减去 5?可能有比这更简单的解决方案,如果没有,我该如何使用替代解决方案来解决?
get_data.php
$id = $_COOKIE["currentID"];
$filepath = 'stories/'.$id.'.txt';
if (file_exists($filepath)) {
$lastmodif = isset($_GET['timestamp']) ? $_GET['timestamp'] : 0;
$currentmodif = filemtime($filepath);
while($currentmodif <= $lastmodif){
sleep(1);
clearstatcache();
$currentmodif = filemtime($filepath);
}
// I've tried:
// Attempt to getting the last five words of .txt file, does NOT work
$str = file_get_contents($filepath);
$words = explode(' ', $str);
$last = join(" ", array_slice($words, -5, 5));
$response = array();
/* $response['data'] = file_get_contents($filepath); */ //use if not attempting to get last 5 words
$response['data'] = $last; //part of "what I've tried"
$response['timestamp'] = $currentmodif;
echo json_encode($response);
}
else{
// if file doesn't exist
echo('nada data, son.');
}
?>
application.js(用于上下文)
$(function(){
$.longpolling({
pollURL: './get_data.php',
successFunction: pollSuccess,
errorFunction: pollError
});
});
function pollSuccess(data, textStatus, jqXHR){
var json = eval('(' + data + ')');
$('#response').html(json['data']);
document.getElementById('notificationsound').play();
console.log('file updated');
}
function pollError(jqXHR, textStatus, errorThrown){
console.log('Long Polling Error: ' + textStatus);
}
【问题讨论】:
标签: javascript php string output file-get-contents