简体   繁体   中英

PHP callback function for similar exec() every output line real time

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.

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM