SunnyBoy's avatar

IBM Watson Tone Analyzer with Laravel 5.7

I am trying to figure out how to use the tone analyzer within laravel project since couple of days. But not sure how to display it to the frontend. Need some help if in case anyone has tried??? I am able to get the data but not able to iterate thru the json object containing the array. FRUSTRATED

Controller

public function getToneData(Request $request)
    {
        // initialize credentials
        $username = env('WATSON_USERNAME');
        $password = env('WATSON_PASSWORD');
        $data = json_encode(array('text' => $request->text));
        $URL = 'https://gateway.watsonplatform.net/tone-analyzer/api/v3/tone?version=2017-09-21';

        // initialize session
        $ch = curl_init();

        // set session
        curl_setopt($ch, CURLOPT_URL, $URL);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
        curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        $response = curl_exec($ch);
        curl_close($ch);

        return view('home', compact('response'));
    }

View

    <div class="container">
        <h1>Results:</h1>
        <p>{{ $response }}</p>

    // How to iterate to get tone_name and scores? 

    </div>

Output for "Normal is boring!"

{"document_tone":{"tones":[{"score":0.706991,"tone_id":"sadness","tone_name":"Sadness"},{"score":0.955445,"tone_id":"analytical","tone_name":"Analytical"}]}}
0 likes
3 replies
jlrdw's avatar
jlrdw
Best Answer
Level 75

Since you already know the names:

document_tone and tones it's a less of a headache to loop:

Say the variable was $param that holds:

{"document_tone":{"tones":[{"score":0.706991,"tone_id":"sadness","tone_name":"Sadness"},{"score":0.955445,"tone_id":"analytical","tone_name":"Analytical"}]}}

So do:

$json = json_decode($param, true);

then:

foreach ($json as $item) {
            foreach ($item["tones"] as $value) {
                echo $value['tone_name'] . "  -  " . $value["score"] . "<br>";
            }
        }

Here's the output

Sadness  -  0.706991
Analytical  -  0.955445

Just example in controller pass $json to your view as needed, in your case response.

1 like
SunnyBoy's avatar

@JLRDW - Yes it worked the missing key was json_decode(). Thanks! Now I am just getting curious how to use Guzzle to connect! ?

jlrdw's avatar

I'd say start a new topic for that.

Please or to participate in this conversation.