Text to speech - PHP - How to save the .mp3 file?

To convert Text to speech in PHP we use the parameters:
‘model’ => ‘tts-1’,
‘input’ => ‘The quick brown fox jumped over the lazy dog.’,
‘voice’ => ‘alloy’,
]); // audio file content as string

How to save the .mp3 file using PHP?
Does anyone have an example?

  • Initializes a cURL session.
  • Sets various options for the cURL session:
    • URL to make the request to.
    • Headers for authorization and content type.
    • The data to be sent in JSON format.
    • Option to return the result as a string.
  • Executes the cURL session and captures the output.
  • Checks for errors and prints any that occur.
  • Saves the output as speech.mp3.
  • Closes the cURL session.

$openai_api_key = 'YOUR_OPENAI_API_KEY'; // Replace with your actual API key

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, 'https://api.openai.com/v1/audio/speech');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Authorization: Bearer ' . $openai_api_key,
    'Content-Type: application/json'
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array(
    'model' => 'tts-1',
    'input' => 'Today is a wonderful day to build something people love!',
    'voice' => 'alloy'

$result = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
} else {
    // Saving the result as an MP3 file
    file_put_contents('speech.mp3', $result);


I’ve yet test it but much sure that will work. if not get help from ChatGPT , if still didn’t work then get back to me.

Thanks a lot for the help!
And immediate answer to my question.
Worked perfectly!!!