4

I was searching for a php function or workaround for that would allow you to make a callback function for every line the execution outputs. The best I could find was proc_open(), but it only allowed me to output per specified byte when calling fgets(), to get the output. If I put the bytes too small in fgets() it breaks one line into multiple lines; too large will delay the callback.

Is there a function out there in PHP that allows me to call my callback function, similar to proc_open, per output line? Exec() function is a great example since it can puts each line into an array, but it has no option to give callback as it makes each index.

2
  • 1
    Wouldn't iterating over each line and then calling the callback function manually work? Commented Jun 25, 2012 at 8:18
  • @Ikke Sorry to not mention, but I'm trying to encode a video using CLI. The output gives me completion percentage per line and I want to call the callback to store the percentage to the database per line. proc_open() gives me 3 to 4 lines at a time. I have to keep playing around with fgets()'s return per specified byte parameter to get it right. Just wanted to see if there was another way around that. Commented Jun 25, 2012 at 8:29

1 Answer 1

5

You can make your own by just calling the each lines returned from exec with a callback. See bellow

function exec_callback($command, $callback){
    $array = array();
    exec($command, $array, $ret);
    if(!empty($array)){
        foreach ($array as $line){
            call_user_func($callback, $line);
        }
    }
}

// example to use
function print_lines($line){
    echo "> $line\n";
}

exec_callback("ls -l /", 'print_lines');
Sign up to request clarification or add additional context in comments.

1 Comment

Doesn't this wait for the exec to complete? I think the question is how to run a function on every line output from the exec command as it comes in and not wait until the entire thing finishes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.