I had the same problem, but for the decoding command
At first and general, you can get the error message by redirecting stderr to stdout.
$cmd = "/usr/bin/gpg -a --recipient $to -e -o $outfile $infile 2>&1";
Then you can modify gpg's parameters to suit your needs. Because I had a files encrypted with a key with pass phrase I had to add several parameters.
I started with
gpg -o $out -d $path
But it complained, that it can not open tty, then with --no-tty it outputs some other errors and finally the command for decoding files with key with pass phrase is
gpg --batch --passphrase $pass_phrase --no-tty -o $outfile -d $path_to_encoded_file
I hope this helps someone.