Google TTS API: Encoding GET request with PHP

2019-05-18 08:45发布

--- SOLVED ---

Problem solved. Solution is simple:

file_get_contents("http://translate.google.com/translate_tts?tl=de&q=".urlencode($str)."&ie=UTF-8")

To those coming here from search engine: Make sure you set the file charset to UTF-8, include the ie=UTF-8 parameter into the URL, urlencode your string. Everything should be fine then.

ORIGINAL POST WAS:

I have a problem with making PHP send a correctly encoded GET request to the Google TTS API.

$str='This is a German string which contains crazy Umlaute like ä (like in Häuser) or ü (like in Übermensch). Sehr deutsch halt.';
file_get_contents("http://translate.google.com/translate_tts?tl=de&q=".$str."&ie=UTF-8");

All included PHP files are encoded in UTF-8 (no byte order marks). What Google TTS returns to me is an MP3 file which spells the "Umlaute" not like Übermensch, but like A~1/4bermensch. This problem has nothing to do with the client side.

I think Google is expecting an ASCII string, this might be my problem? When I type the GET line into my browser manually however, it spells everything correctly. See also:

stackoverflow - Google TTS API for Arabic, Chinese and Greek

Thanks for help!!

1条回答
ゆ 、 Hurt°
2楼-- · 2019-05-18 09:32

You have to set the encoding URL Parameter &ie=utf-8 and the encoding of the python file itself to: #coding: utf-8 and be sure to safe the .py file with utf-8 encoding (not iso-8859-1).

查看更多
登录 后发表回答