The command may not finish before the function return if the stream is not set to blocking mode. You may have to set the stream to blocking mode in order to get any output from the command.
<?php
// [Open connection]
// ...
$stream = ssh2_exec($connection, 'ps ax');
stream_set_blocking($stream, true);
// The command may not finish properly if the stream is not read to end
$output = stream_get_contents($stream);
// ...
// [Close stream and connection]
?>