开发者

php timed (duration) display

So I want to have an array in a .txt file with separate lines and pull each line and display it after a certain duration... I don't know if I need to mix ajax with php or if this can just be straight php.

开发者_如何学运维

Is foreach the best way to do this?

<?php

    $x=file("sayings.txt");
    foreach ($x as $value)
      {
      echo $value . "<br />";
      }
    ?> 

Where can I implement a duration.. is there a wait?

like this:

{ echo $value . "

"; wait 1000 //miliseconds }

Went with javascript for this one.. its here if you want the answer/code: javascript array timed


Service side solution

Server side you could do this :

<?php

$x=file("sayings.txt");
foreach ($x as $value)
{
    echo $value . "<br />";//Send the output
    flush();               //Make sure it's outputted
    sleep(1);              //Sleep 1 second
}
?> 

Client side solution

But, you can also use Ajax call with a parameter (an index) that will return the next index every call. You can do that with a SetTimeOut in Javascript.

<script type="text/javascript">
var arrayIndex = 0;
function getArrayData()
{
    var dataFromServer="";
    $.get("myServerPage.php", { 'arrayIndex': arrayIndex },
         function(data){
         alert("Line : " + data);
         arrayIndex++;
         var t=setTimeout("getArrayData()",1000);//Every 1 second
     });
   
}
</script>

In myServerPage.php you just have to check the $_GET to check the index and to output the good line. (Validate if the array index is ok). Also, in the server side, once you have finish find that the array is not good this can be the trigger to stop and you just need to return a data to the client (instead of just the line) and will tell the javascript to stop. That's it. Hope it help you.


I am assuming you are running this in a browser.

Its probably best to do it on client side using javascript. You have much more control of what happens on the client side. You wont need ajax either unless your data is changing.

You can kinda of do it on the PHP side, but you may run into buffering problems (Look at the manual for output buffering). Also the rest of the page wont load as you are going through your sleep() loop.


<?php

    $x=file("sayings.txt");
    foreach ($x as $value)
      {
      echo $value . "<br />";
      sleep(1); //wait 1000ms
      echo str_repeat(" ", 50000); //Send output buffer
      flush();
      }
    ?> 


You may also look at flush

<?php

$x=file("sayings.txt");
foreach ($x as $value)
{
    echo $value . "<br />";
    flush();   // send the content to the browser
    sleep(1);  // sleep one second
}
?> 

With this implementation, a change in savings.txt during the execution won't change the output, as the file content is buffered.

You can also look for AJAX, wich will re-fetch the file and get and updated content.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜