Sentiment Analysis using Natural Language API in PHP

Customer feedback helps to build a better product and monitor a business. But, if you are getting tons of feedback then it’s hard to analyze them manually. To make this analysis automate, you can go for sentiment analysis.

Sentiment analysis is performed on textual data submitted by customers in the form of feedback, comments, or reviews. In order to perform sentiment analysis, the natural language processing technique is used. Through this analysis, one can determine whether the document(sentence, text) is positive, negative, or neutral.

In terms of business, data is the most important. Once you know the nature of customer’s sentiments based on data, you can pick up the right direction for your business.

Google Cloud provides a Natural Language API which performs sentiment analysis, entity analysis, entity sentiment analysis, content classification, and syntax analysis. Under the hood, Google uses the machine learning technique and gives us a final result.

In this article, we study performing sentiment analysis using Natural Language API in PHP. To start with integration, you need to first create a service account on Google. The service account keys will be used to authenticate your account with Google.

Creating a Service Account

You have to follow a few steps to create the service account and download the file that contains your credentials. I am writing the steps below from Google Docs.

Create a service account:

  • In the Cloud Console, go to the Create service account page.
  • Select a project.
  • In the Service account name field, enter a name. The Cloud Console fills in the Service account ID field based on this name. In the Service account description field, enter a description.
  • Click Create.
  • Click the Select a role field. Under Quick access, click Basic, then click Owner.
  • Click Continue.
  • Click Done to finish creating the service account.

Create a service account key:

  • In the Cloud Console, click the email address for the service account that you created.
  • Click Keys.
  • Click Add key, then click Create new key.
  • Click Create. A JSON key file is downloaded to your computer.
  • Click Close.

On the selected project, you need to enable Cloud Natural Language API via the API Library section. The Natural Language API is part of Google Cloud so you will require to enable billing on your account.

Sentiment Analysis using Natural Language API

In the previous steps, you got the JSON file containing your credentials. Copy this JSON file into your project directory. Store this file in a safe place. Remove this file from the git commit using the .gitignore.

Next, install the Cloud Language package provided by Google. Run the command below for installation.

composer require google/cloud-language

Upon package installation, you can authenticate your account with the credentials as follows.

<?php
require_once "vendor/autoload.php";

use Google\Cloud\Language\LanguageClient;

try {
	$language = new LanguageClient([
	    'keyFilePath' => 'JSON_KEY_FILE_PATH',
	]);
} catch(Exception $e) {
    echo $e->getMessage();
}

If everything is done correctly, you can call the Natural Language API through this $language object. For instance, in the below code, I am doing sentiment analysis and printing out whether the text is positive, negative, or neutral.

<?php
require_once "vendor/autoload.php";

use Google\Cloud\Language\LanguageClient;

try {
	$language = new LanguageClient([
	    'keyFilePath' => 'JSON_KEY_FILE_PATH',
	]);

	$annotation = $language->analyzeSentiment('Google Cloud Platform is a powerful tool.');
	print_r($annotation->sentiment());
	// Check the sentiment.
	if ($annotation->sentiment()['score'] > 0) {
        echo "This is a positive message.";
    } elseif ($annotation->sentiment()['score'] < 0) {
        echo "This is a negative message.";
    } else {
        echo "This is a neutral message.";
    }
} catch(Exception $e) {
    echo $e->getMessage();
}

If you print the response array, it has 2 keys – magnitude and score. On the basis of score value, you get to know the attitude expressed within the text.

Entity Analysis

Entity Analysis finds named entities in the text, entity types, salience, mentions for each entity, and other properties in the document. In general, if something is a noun, it qualifies as an “entity”.

$annotation = $language->analyzeEntities('Google Cloud Platform is a powerful tool.');
print_r($annotation->entities());
foreach ($annotation->entities() as $entity) {
    echo $entity['type'];
}

Here, I print a type of entity(for example if the entity is a person, location, consumer good, etc.). You can analyze the result by printing the array.

The code written in the above examples is used to perform sentiment analysis and entity analysis. I also recommend reading the documentation of Natural Language API.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

3 thoughts on “Sentiment Analysis using Natural Language API in PHP

Leave a Reply

Your email address will not be published. Required fields are marked *