Google TTS API: Encoding GET request with PHP

2019-05-18 09:24发布

问题:

--- 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:

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).