开发者

PHP realtime output of content

开发者 https://www.devze.com 2023-01-27 13:24 出处:网络
I\'m trying to display some content in real time to my visitors using a loop. Problem is that the content is added to the output instead of being replaced with the new one. Here\'s an example of code

I'm trying to display some content in real time to my visitors using a loop. Problem is that the content is added to the output instead of being replaced with the new one. Here's an example of code which counts from 10 to 0. The output shows the whole set of results instead of开发者_如何学JAVA counting backwards. I mean, I don't want to see all numbers shown just each number as the counter goes.

ob_end_flush ();
        //start buffering
        ob_start ();

        echo str_pad ( '', 1024 ); // minimum start for Safari
        for ( $i = 10; $i > 0; $i --) {
            echo str_pad ( "$i<br>\n", 8 );
            ob_flush ();
            flush ();
            sleep ( 1 );
        }
        die ();


This can not be achieved with PHP alone, as to alter what is rendered in the browser requires some client side intervention.

How you go about this division of labour depends upon what is needed.

If your code is all of it, then you would be far better off writing a JS routine to count down the numbers in a timed fashion.

If PHP is required in some other fashion to generate the numbers then the decision needs to be taken as to whether you can split the generation of the update in to multiple PHP calls or if it has to be from within the single PHP call due to actions taking forth within that call.

If the former, you can separate it, which is the ideal situation - then the procedure is to setup AJAX calls to retrieve updated information periodically.

If the latter and it must be from a single page, then the connection must be kept open with new content generated.

In this case, to get new content to replace old, JS code must handle this. Either code running periodically upon the page can check for new content and update accordingly, or a little trick can be played injecting code that performs the update.

Sending inline <script> content that performs the update instead of new display elements works well, if a little untidy, as the browser receives the new <script> element it is run. This is the only way I am aware of that a push-update can be made to a web page without plugins.


There might be a trick or something (just thought of one or two) but the most appropriate way to do it is with an ajax autoupdate from the browser. Like this pattern description.


We didnt do this in PHP, in fact using js. ( with Stacker help ) you can reverse the count

But am sure you could adopt, sorry if this doesnt answer your question.

Demo here on our dev site < link >

You can also ( again may not be pertinent, use jquery to refresh a div element )

0

精彩评论

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

关注公众号