Question:
I'm using a Text to Speech service and I would like to use it in a php that I'm building.
The problem is that I've never done what the api asks for and I don't even know where to start.
this type of information is provided in the documentation.
GET https://txttovoice.org/v/tts?v=1.1&text=Hello+world
Headers:
Authorization: Bearer TOKEN_DE_ACESSO
Accept-Language: pt-BR
How do I make a php send these headers on this link and receive a download of a file in exchange and save it in the same folder as my php file is?
in the api it provides a curl too
curl -k -H "Authorization: Bearer TOKEN_DE_ACESSO" -H "Accept-language: pt-BR" https://txttovoice.org/v/tts?v=1.1&text=Hello+world" -o arquivo.wav
what would be the simplest way for me to make this work?
Answer:
Let's translate the CURL:
-
curl
: Starts CURL. -
-k
: Set to insecure mode, not checking SSL. -
-H "Authorization: Bearer TOKEN_DE_ACESSO"
Sets theAuthorization
header with the value ofBearer TOKEN_DE_ACESSO
. -
-H "Accept-language: pt-BR"
: SetAccept-language
header with value ofpt-BR
-
"https://txttovoice.org/v/tts?v=1.1&text=Hello+world"
: Defines the website you want to connect to. -
-o arquivo.wav
: Sets the output location of the result.
Now let's port this to PHP, in the same order:
// Inicia o CURL:
$ch = curl_init();
// Adiciona as opções:
curl_setopt_array($ch, [
// Modo inseguro:
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
// Adiciona os cabeçalhos:
CURLOPT_HTTPHEADER => [
'Authorization: Bearer TOKEN_DE_ACESSO',
'Accept-language: pt-BR',
],
// Define o URL para se conectar:
CURLOPT_URL => 'https://txttovoice.org/v/tts?v=1.1&text=Hello+world',
// Saída:
CURLOPT_RETURNTRANSFER => true
]);
// Executa:
$resultado = curl_exec($ch);
// Encerra CURL:
curl_close($ch);
The $resultado
variable will have the result returned by the website, so if you want to save it somewhere use file_put_contents()
.
file_put_contents('nome_arquivo.formato', $resultado);
This is one of the easiest ways, however there may be memory related issues and so you can handle storage directly in CURL, which will fix the problem.
For this the solution is to use CURLOPT_FILE
, which will basically do exactly what -o
does.
$escreverArquivo = fopen('nome_arquivo.formato', 'w+');
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer TOKEN_DE_ACESSO',
'Accept-language: pt-BR',
],
CURLOPT_URL => 'https://txttovoice.org/v/tts?v=1.1&text=Hello+world',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FILE => $escreverArquivo
]);
curl_exec($ch);
curl_close($ch);
fclose($escreverArquivo);
Remember that the TOKEN_DE_ACESSO
must be the token
, which is usually obtained in a previous request, in the case of OAuth, for example. This should be mentioned in the API documentation, but it wasn't mentioned in the question so you could answer.