Since the output is generated before the exit status is known, you'll have to store it somewhere.
One possibility is to store it in a shell variable:
output=$(php /path/to/script.php)
if [ $? -ne 0 ]; then
printf "%s\n" "$output"
fi
This doesn't completely preserve the script's output (it removes trailing blank lines), but that's ok for this use case. If you want to preserve trailing blank lines:
output=$(php /path/to/script.php; ret=$?; echo a; exit $ret)
if [ $? -ne 0 ]; then
printf "%s" "${output%a}"
fi
If there's potentially a lot of output, you might prefer to store it in a temporary file instead:
output_file=$(mktemp /var/tmp/script.XXXXXXXXXX.out)
php /path/to/script.php >>"$output_file"
ret=$?
if [ $ret -ne 0 ]; then
echo "script.php failed (status $ret), see the output in $output_file"
fi