How to Implement Sentiment Analysis & Classification in PHP

Cloudmersive
1 min readMar 28, 2023

--

With the proper tools, you can gain useful insights from customer reviews and other voluntary text inputs from your website.

Using the code examples below, you can quickly and easily implement a free-to-use Sentiment Analysis & Classification API which will help determine if an input text string contains positive, negative or neutral views towards any given subject. The underlying resource will also provide a numerical score (on a scale from -1.0 to +1.0) to accompany each of these classifications.

Let’s start by installing the Client SDK. We can run the following command to do so:

composer require cloudmersive/cloudmersive_nlp_api_client

Next, let’s copy & paste from the PHP code examples below to structure our API calls. At this stage, we’ll need to have a free-tier API key ready to authenticate each call (you can get one by registering a free account on our website):

<?php
require_once(__DIR__ . '/vendor/autoload.php');

// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');



$apiInstance = new Swagger\Client\Api\AnalyticsApi(


new GuzzleHttp\Client(),
$config
);
$input = new \Swagger\Client\Model\SentimentAnalysisRequest(); // \Swagger\Client\Model\SentimentAnalysisRequest | Input sentiment analysis request

try {
$result = $apiInstance->analyticsSentiment($input);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling AnalyticsApi->analyticsSentiment: ', $e->getMessage(), PHP_EOL;
}
?>

That’s all the code you’ll need! When structuring your request, include your text in a “TextToAnalyze” string (like so):

{
"TextToAnalyze": "string"
}

--

--

Cloudmersive
Cloudmersive

Written by Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.

No responses yet