Strawberry
Strawberry

Reputation: 67968

Is it possible to have PHP print in the while loop before it finishes processing?

for($x=0;$x<100000;$x++) {
    echo "hello $x";
}

So, normally, it will finish processing everything first and then print everything at once. Is there a way to just keep printing the message as the command is sent, so that I'll see a new hello $x appended one by one or do I have to use jQuery/JavaScript?

Update:

I ask because I'm trying to run a long test script and have it show all the results 1 by 1 on the browser so I don't have to go check the logs and could just visually see the color coded results. I'm trying to make a similar effect to this: http://tools.css3.info/selectors-test/test.html If anyone could provide a short sample of the jQuery (if it has to be done this way), I would appreciate it.

Upvotes: 2

Views: 128

Answers (2)

bfavaretto
bfavaretto

Reputation: 71939

Although it's possible by controlling the output buffer, I wouldn't do that, mainly because it will delay the JavaScript DOMReady event.

If you're looking for a visual effect, you should use JavaScript (but I don't see any reason for Ajax based on what your question says). It can be accomplished with a simple setInterval. Considering an initially empty <div id="hello">:

var i = 0;
var timer = setInterval(function(){
    if(i == 10000) {
        clearInterval(timer);
        return;
    }
    var div = document.getElementById('hello');
    div.innerHTML += 'hello ' + i + '<br>';
    i++;
}, 250);

I just saw your edit, and now I think you actually should use Ajax! The example you linked to does. Basically, you have to setup a test queue in JavaScript, where each test has an unique URL. Then it's just a matter of firing one request at a time with Ajax (jQuery and $.get would be the easiest way to go). The following assumes an <ul> instead of the div from my previous example, and that the server will respond with a success or failure message for each test:

var tests = [
    'http://example.com/test1',
    'http://example.com/test2',
    'http://example.com/test3',
];

function processQueue() {
    if(tests.length > 0) {
        var test = tests.shift();
        $.get(test, function(response) {
            $('#some_ul').append('<li>' + response + '</li>');
            processQueue();
        });    
    }
}

processQueue();

Upvotes: 3

John Carter
John Carter

Reputation: 55369

Yes, if you disable output buffering: http://php.net/manual/en/book.outcontrol.php

But as @Blender suggests you'd probably be better off doing this with AJAX (commonly done using jQuery).

Upvotes: 1

Related Questions