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"}]}}