PHP使用file_get_contents从.txt文件中获取最后五个单词

时间:2015-02-01 18:47:28

标签: javascript php string output file-get-contents

我正在寻找一种功能性的方法来读取 last ,比如,在长轮询时使用file_get_contents从.txt文件中获取5个单词。我已尝试使用下面的评论代码处理解决方案,但它打破了长轮询 - 在显示.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);
}

1 个答案:

答案 0 :(得分:0)

为什么不这样做:

$lastfive = explode(" ", trim(preg_replace("/^([\s\S]+)(( ([^ ]+)){5})$/m", "$2", $code)));

此外,在解析从服务器检索的代码时,您应该从不使用eval。请尝试使用JSON.parse(data)

相关问题