将终端输出结果写入php中的文件

I have run my commands using system and i would like for it copy the terminal results to a file called output.txt. When I run my php script on the browser it displays the result but not in the output.txt the file is empty.

echo '<pre>';

$last_line = system('ruby /home/simon/ruby-grok/examples/result.rb', $retval);

echo '</pre>';

$out = fopen('output.txt', 'w'); //output handler
fputs($out,$last_line); //writing output operation
fclose($out); 

Code seems fine. Does script have the permission to write in that specific file? And can you try instead of

$out = fopen('output.txt', 'w'); //output handler
fputs($out,$last_line); //writing output operation
fclose($out); 

to put this:

file_put_contents('output.txt',$last_line);

edit:

btw i forgot to ask. what output your browser displays? is there any data in $out variable?

Using backticks is much better.

$variable = `ls -l`;

and then:

$out = fopen('output.txt', 'w'); //output handler

fputs($out,$variable); //writing output operation

fclose($out); 

or:

file_put_content('output.txt',$variable);