blade19899
blade19899

Reputation: 767

IBM Watson Text To Speech PHP API Issue: No JSON object could be decoded

My current PHP code does not seem to work for the IBM Watson Text To Speech.

The below code returns the following output:

{
   "code_description": "Bad Request", 
   "code": 400, 
   "error": "No JSON object could be decoded"
}"

I have been adding and removing several cURL options, to get it to work, but it still returns the aforementioned error.

<?php

$data="Hello World";

$ch = curl_init();

curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_URL,"https://stream.watsonplatform.net/text-to-speech/api/v1/synthesize");
curl_setopt($ch, CURLOPT_USERPWD, "$USERNAME:$password");
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLINFO_HEADER_OUT, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER,
    array(
        "Content-Type: application/json",
        "Accept: audio/webm"
    )
);

$server_output = curl_exec($ch);

$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

$info = curl_getinfo($ch);

curl_close ($ch);

Which header am I supposed to add/remove to get it to work?

Upvotes: 3

Views: 436

Answers (2)

Steph
Steph

Reputation: 1

Since this is the only question found by google for this common problem ... please have in mind that instead of the CURLOPT_USERPWD (which is quite fine for watson without any base64_encode in most cases), the problem here is quit simple and the reply states everything needed: "No JSON object could be decoded"

$data="Hello World"; # <- THIS IS NOT JSON !!!
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);

# try: 
$data='{"text":"Hello World"}';

(that's the simplest way to state JSON)

Upvotes: 0

Tarik1322
Tarik1322

Reputation: 90

@blade19899

change this line:

From: curl_setopt($ch, CURLOPT_USERPWD, "$USERNAME:$password");

To: curl_setopt($ch, CURLOPT_USERPWD, base64_encode("$USERNAME:$password"));

For security reasons a base64 string is expected in authorization header. Hope this helps you.

Upvotes: 0

Related Questions