如何在PHP中逐行输出命令执行?

时间:2015-05-13 13:37:16

标签: php buffering output-buffering

我试图通过以下代码逐行生成命令执行的输出。 当我运行这个时,我得到输出,但不是逐行,而是在每次冲洗时打印整个缓冲区。我尝试过使用ob_start& ob_clean但它没有用。



<?php

    //header('Content-Encoding: none;');
	//header('Content-Type: text/event-stream');
	header('Cache-Control: no-cache');
        set_time_limit(0);
        $handle = popen("dir", "r");

        if (ob_get_level() == 0) 
            ob_start();
	
        while(!feof($handle)) {
			$buffer = fgets($handle,4096);
            $buffer = trim(htmlspecialchars($buffer));
			echo $buffer;
			//echo str_pad('', 4096);    
			ob_flush();
            flush();
            sleep(1);
        }
        pclose($handle);
       ob_end_flush();
?>
&#13;
&#13;
&#13;

在前端我使用此代码显示输出:

&#13;
&#13;
<html>
   <head>
     <title>Ajax Streaming Test</title>
   </head>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
   <body>
     <center><a href="#" id="test">Test Ajax Streaming</a></center>
	 <pre><div id="mydiv"> </div></pre>
     <script type="text/javascript">
       document.getElementById('test').onclick = function() {
         xhr = new XMLHttpRequest();
         xhr.open("GET", "new4.php", true);
		 xhr.onprogress = function(e) {
          //alert(e.currentTarget.responseText);  
		 document.getElementById("mydiv").innerHTML += xhr.responseText+"<br>";
		  
         }
         xhr.onreadystatechange = function() {
           if (xhr.readyState == 4) {
             console.log("Complete = " + xhr.responseText);
           }
         }
         xhr.send();
		 var res = xhr.responseText;
       };
     </script>
   </body>
</html>
&#13;
&#13;
&#13;

0 个答案:

没有答案