English (UK) Text-to-Speech API in PHP
You need to generate English (UK) speech from text in a PHP application and ship it fast. By the end of this guide, you’ll POST text to Woord’s Text-to-Speech convert endpoint, capture the audio_src for English (UK), and play or store the resulting MP3—all using PHP and one additional JavaScript example for teams mixing stacks.
What you will build and what you need
You will build a minimal server-side integration that sends text, selects an English (UK) voice, and receives a direct MP3 URL. You will:
- Send a POST request to the Woord convert endpoint with form fields, not JSON.
- Authenticate with a Bearer token.
- Parse the JSON envelope to retrieve audio_src.
- Optionally stream or download the MP3 for playback or storage.
Requirements:
- A Woord account and API key. Free plans cannot call the convert endpoint—register for the appropriate plan.
- PHP 7.4+ with ext-curl or allow_url_fopen enabled (depending on approach).
- Network access from your server to api.getwoord.com and getwoord.s3.amazonaws.com.
Origin catalog facts for this locale and endpoint
- Language: English (UK)
- language=en_GB
- gender_voice=male (docs default)
- Sample text from editorial/docs for this locale: Hello World
- curl: curl "https://www.getwoord.com/api/convert" -X POST -H "Accept: application/json" -H "Authorization: Bearer YOUR_KEY" --data "text=Hello+World&gender_voice=male&language=en_GB&speakingRate=1.00"
- Official convert envelope:
{ "message": "Your audio has been created!", "audio_src": "https://getwoord.s3.amazonaws.com/4273352455515882618255eaaf3c1cbdbe0.55443890.mp3", "error": false } - The S3 filename is the docs fixture. The reader’s audio_src will be a new key. Do not hotlink this URL.
Endpoint overview
The Woord convert endpoint accepts form-encoded data and returns a JSON envelope with a message, audio_src, and error flag.
- URL: https://www.getwoord.com/api/convert
- Method: POST
- Auth: Authorization: Bearer YOUR_API_KEY
- Content: form fields (application/x-www-form-urlencoded or multipart/form-data)
- Required fields for this tutorial:
- text: The input string you want spoken. Example: Hello World
- gender_voice: male
- language: en_GB
Notes:
- Send form fields, not JSON. Do not post a JSON body.
- The official sample also shows speakingRate=1.00. You can copy the sample for a quick test; this guide focuses on the required fields above.
- Free plans cannot call the convert endpoint. Use a paid plan before testing convert.
Quick test with cURL
Official cURL sample (copy exactly for a test)
curl "https://www.getwoord.com/api/convert" -X POST -H "Accept: application/json" -H "Authorization: Bearer YOUR_KEY" --data "text=Hello+World&gender_voice=male&language=en_GB&speakingRate=1.00"
Replace the Authorization header with your real Bearer token when you run it. The command posts form-encoded data and requests JSON back.
Understanding the response
Official JSON envelope
What matters in practice:
- message: Human-readable status.
- audio_src: A direct HTTPS link to the generated MP3 on S3. Your call will return a new key; do not rely on the fixture URL above.
- error: Boolean flag you can check before attempting to play or download audio.
Do not hotlink the fixture URL in your app. Always use the audio_src returned by your request.
PHP integration (curl_init)
This snippet posts the required form fields for English (UK) and returns the audio_src so you can redirect the client, download, or embed a player. It uses curl_init to set headers and send application/x-www-form-urlencoded data.
PHP (curl_init)
Implementation notes:
- Use http_build_query to ensure correct percent-encoding (e.g., spaces to + and other characters to %XX).
- Always check error and presence of audio_src before using the link.
- If you need to persist the MP3, download audio_src immediately to your storage and serve it from your domain to avoid hotlinking.
JavaScript example (Node.js, fetch)
If you prefer JavaScript on the server side, this Node.js example posts FormData and reads audio_src. Keep your API key on the server; do not expose it in a browser client.
JavaScript (Node.js with undici or node-fetch)
// Requires Node 18+ (global fetch) or install undici/node-fetch.
// Run: node tts.js
const endpoint = 'https://www.getwoord.com/api/convert';
const apiKey = 'YOUR_API_KEY';
async function convertTextToSpeech() {
const params = new URLSearchParams();
params.set('text', 'Hello World');
params.set('gender_voice', 'male');
params.set('language', 'en_GB');
const res = await fetch(endpoint, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Bearer ' + apiKey,
'Content-Type': 'application/x-www-form-urlencoded',
},
body: params.toString(),
});
if (!res.ok) {
const errText = await res.text().catch(() => '');
throw new Error('Non-2xx response: ' + res.status + ' ' + errText);
}
const json = await res.json();
if (json.error) {
throw new Error('API error: ' + (json.message || 'Unknown'));
}
if (!json.audio_src) {
throw new Error('Missing audio_src in response');
}
console.log('Message:', json.message);
console.log('Audio URL:', json.audio_src);
// Optional: download the MP3 to disk
// const audioRes = await fetch(json.audio_src);
// const fileStream = require('node:fs').createWriteStream('output.mp3');
// await new Promise((resolve, reject) => {
// audioRes.body.pipe(fileStream);
// audioRes.body.on('error', reject);
// fileStream.on('finish', resolve);
// });
// console.log('Saved to output.mp3');
}
convertTextToSpeech().catch((e) => {
console.error('Failed:', e.message);
process.exit(1);
});
Tip: Prefer application/x-www-form-urlencoded for compact, predictable bodies and simple logging. FormData multipart also works, but it adds boundary overhead and is not required here.
Working with audio_src safely
The audio_src is a direct HTTPS link to your generated MP3. Practical handling options:
- Immediate playback: Return audio_src to the browser and set it as the src for an HTML audio element. This is simplest but exposes the S3 link to clients.
- Server-side fetch and re-serve: Download the MP3 to your server or object storage, then serve from your domain. This avoids hotlinking and lets you set cache headers.
- Temporary redirect: Create a short-lived redirect endpoint that temporarily 302-redirects to audio_src if you need to obfuscate URLs without storing files.
Caching and headers:
- Store a mapping from your input text (plus parameters like language and gender_voice) to the resulting audio_src or your stored file key.
- Set CDN or HTTP cache headers on your hosted MP3s if they are reused across users.
- When using the S3 link, recognize it may be long-lived but should not be considered permanent; persisting the audio removes that risk.
Error handling and troubleshooting
- 401/403 Auth errors: Ensure Authorization: Bearer YOUR_API_KEY and no extra whitespace. Do not send Basic or query-string auth.
- 415/400 Content-type issues: Send form data, not JSON. Use application/x-www-form-urlencoded and encode text with http_build_query or URLSearchParams.
- Missing audio_src: Check error is false. If error is true, read message for context.
- Free plan: Free cannot call convert. Upgrade before testing this endpoint.
- Language mismatch: Use language=en_GB for English (UK) as shown in this guide.
- Timeouts: Client timeouts of 30–60 seconds are typical. If you run into timeouts, retry with backoff and consider performing the request off the main web thread.
End-to-end flow for PHP backends
1) Accept input
Accept user text (POST body), validate it, and normalize whitespace. For English (UK), you can default gender_voice=male and language=en_GB when no override is provided.
2) Generate or reuse audio
Build a deterministic cache key from the concatenation of text, language=en_GB, and gender_voice=male. If you have previously generated audio and stored it, reuse it to save an API call. Otherwise, call convert and store the resulting MP3.
3) Return a stable URL
Return a URL under your domain where the MP3 is served. If you return audio_src directly, remember that the link can change and is controlled by the provider—store your own copy when stability is required.
Security and operational notes
- Never embed your API key in client-side code. Keep it server-side.
- Log only high-level request metadata. Do not log full audio_src or long texts if they may contain sensitive data.
- Add input validation: enforce max length and allowed characters to avoid accidental abuse or excessively long audio generation.
- Observability: Log timing for convert calls and flag slow responses to detect regressions.
FAQ
Q: Which fields are required for English (UK) TTS in this guide?
A: Send text, gender_voice=male, and language=en_GB as form fields. Authenticate with a Bearer token.
Q: Can I call convert on a free plan?
A: No. Free cannot call this endpoint. Use a paid plan before integrating convert.
Q: Should I post JSON or form data?
A: Post form data. Use application/x-www-form-urlencoded or multipart/form-data. Do not send JSON.
Q: How do I play the audio in a web page?
A: After you receive audio_src, set it as the src attribute on an HTML audio element. For stability and control, consider downloading the MP3 and serving it from your domain.
Q: Can I adjust speed or voice beyond what’s shown here?
A: The official sample includes speakingRate=1.00. For other options, refer to the API Documentation.
Ready to generate English (UK) speech with PHP? Create your API key and start integrating now: Register. For parameter details and updates, see the official Documentation.
