PHP Classes

How to Implement PHP Sentiment Analysis Using Google Artificial Intelligence API to Process Natural Language Text - PHP OAuth Library package blog

Recommend this page to a friend!
  All package blogs All package blogs   PHP OAuth Library PHP OAuth Library   Blog PHP OAuth Library package blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Implement PHP ...  
  Post a comment Post a comment   See comments See comments (0)   Trackbacks (0)  

Author:

Updated on: 2024-01-10

Posted on: 2024-01-10

Package: PHP OAuth Library

The evolution of artificial intelligence allowed the implementation of more advanced solutions for complex problems like, for instance, the interpretation of human language.

One type of interpretation of human language is the analysis of sentiments expressed by people when they send text messages.

Read this step-by-step tutorial article to learn, for example, PHP code and how to use Google Cloud Natural Language API to analyze human sentiments using text messages from PHP.




Loaded Article

In this article you will learn:

1. Why Sentiment Analysis Can Be Useful In Applications That Process User Messages

2. What a PHP Developer Can Do to Analyse the Sentiments Expressed in User Messages

3. How Can You Implement Sentiment Analysis in PHP by Calling the Google Cloud Natural Language API

4. How Can You Download or Install the PHP OAuth Client Class to Call APIs Using the PHP Composer Tool

1. Why Sentiment Analysis Can Be Useful In Applications That Process User Messages

There are many services on the Internet that can be used to transmit messages between users.

Sometimes, users who are not feeling well send messages that pass negativity and cause bad feelings to other users.

Suppose messages can be analyzed to detect negativity automatically when the messages are sent. In that case, it is possible to ask the user trying to send negative messages to calm down and reconsider how he is writing those messages to be more positive and cause good sentiments.

2. What a PHP Developer Can Do to Analyse the Sentiments Expressed in User Messages

Analyzing text sentences to detect user sentiments is a complex task. It requires good knowledge of text parsing, grammar analysis, expression meaning analysis, and sentence scoring.

All these steps needed to implement good sentiment analysis solutions can be implemented in any modern programming language.

There are some good solutions to implement sentiment analysis in PHP, like, for instance, the packages PHP Sentiment Analyzer and the WordPress Plugin Sentiment Analysis.

Still, it is hard to implement a complete solution that supports many languages users use to write their text messages.

Modern artificial intelligence solutions provided as APIs like the Google Cloud Natural Language API can help to achieve that goal.

3. How Can You Implement Sentiment Analysis in PHP by Calling the Google Cloud Natural Language API

The Google Cloud Natural Language API can be called using the OAuth protocol to obtain an access token necessary to make API calls on behalf of a given authenticated user with a Google account or using an API key.

In this article, I will explain the steps to call the Google Cloud Natural Language API using an OAuth access token.

3.1. Obtain an Access Token to Use in by the PHP Code

The first step is to obtain an access token from the Google Cloud Console. You need to go to the API page and click on the button to activate the API.

Then click on the OAuth consent screen tab and click on the button to create an application.

On the scopes step you need to add the scopes https://www.googleapis.com/auth/cloud-language and https://www.googleapis.com/auth/userinfo.profile .

On the Credentials tab, click on the CREATE CREDENTIALS button and select the OAuth client ID  menu entry.

On the application type, select the Web application menu. On the Authorized redirect URIs input enter the URL of the script that I am showing below in your Web server.

When you are done creating the application, take note of the Client ID and Client secret that appears.

3.2 Calling the Google Cloud Natural Language API

The OAuth Client library package comes with an example script XXX that you can adapt to use in your applications that call the Google Cloud Natural Language API.

Here is the same script with some explanations

3.2.1. Initialize the OAuth client class

    $client = new oauth_client_class;
    
$client->server 'Google';

3.2.2. Set the debug variable to true only if there is something wrong you need to understand and fix

    $client->debug false;
    
$client->debug_http true;
    
$client->redirect_uri 'https://'.$_SERVER['HTTP_HOST'].
        
dirname(strtok($_SERVER['REQUEST_URI'],'?')).'/google_natural_language_sentiment_analysis.php';

3.2.3 Set the client_id and client_secret with credentials obtained from the Google Cloud Console

    $client->client_id ''$application_line __LINE__;
    
$client->client_secret '';
    
    if(
strlen($client->client_id) == 0
    
|| strlen($client->client_secret) == 0)
        die(
'Please go to Google APIs console page '.
            
'https://console.cloud.google.com/apis/library/language.googleapis.com in the API access tab, '.
            
'create a new client ID, and in the line '.$application_line.
            
' set the client_id to Client ID and client_secret with Client Secret. '.
            
'The callback URL must be '.$client->redirect_uri.' but make sure '.
            
'the domain is valid and can be resolved by a public DNS.');

    
/* API permissions
     */
    
$client->scope 'https://www.googleapis.com/auth/cloud-language'.' '.
        
'https://www.googleapis.com/auth/userinfo.profile';

3.2.4 Initialize and call the PHP OAuth client class to call the Google Natural Language API

    if(($success $client->Initialize()))
    {
        if((
$success $client->Process()))
        {
            if(
strlen($client->authorization_error))
            {
                
$client->error $client->authorization_error;
                
$success false;
            }
            elseif(
strlen($client->access_token))
            {

3.2.5 Call the Google account user profile API to get the user name

                $success $client->CallAPI(
                    
'https://www.googleapis.com/oauth2/v1/userinfo',
                    
'GET', array(), array('FailOnAccessError'=>true), $user)
                if($success)
                {

3.2.6 Check if the form to enter the text to analyzed was submitted

                    if(IsSet($_POST['text']))
                    {

3.2.7 Compose the object with the details for the sentiment analysis API call.

                        $document = new stdClass;
                        
$document->content $_POST['text'];
                        
$document->language 'en';
                        
$document->type 'PLAIN_TEXT';
                        
$sentiment_analysis_request = new stdClass;
                        
$sentiment_analysis_request->document $document;
                        
$sentiment_analysis_request->encodingType 'UTF8';

3.2.8 Send the sentiment analysis API call

                        $success $client->CallAPI(
                            
'https://language.googleapis.com/v1/documents:analyzeSentiment',
                            
'POST', array(), array(
                                
'FailOnAccessError'=>true,
                                
'RequestContentType'=>'application/json',
                                
'RequestBody'=>json_encode($sentiment_analysis_request),
                            ), 
$sentiment_analysis);
                    }
                }
            }
        }
        
$success $client->Finalize($success);
    }
    if(
$client->exit)
        exit;
    if(
$success)
    {

3.2.8 If all went well, display the page with the sentiment analysis results and a form to let the user enter a new text message to analyze

?>
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Google Natural Language Sentiment Analysis</title>
</head>
<body>
<h1>Google Natural Language Sentiment Analysis</h1>
<?php
        
if($client->debug)
        {

3.2.9 Show the Google user account API call results in debug mode

            echo '<h1>'HtmlSpecialChars($user->name),
                
', you have logged in successfully with Google!</h1>';
            echo 
'<pre>'HtmlSpecialChars(print_r($user1)), '</pre>';
            echo 
'<pre>Access token: 'HtmlSpecialChars($client->access_token), '</pre>';
        }

3.2.10 If the user submitted the form to analyse the sentiments of a text message, display the results

        if(IsSet($_POST['text']))
        {
                
$analyze_sentiment_score = function($score)
                {
                    if(
$score >= 0.8)
                        return 
'Clearly Positive';
                    if(
$score 0.1)
                        return 
'Positive';
                    if(
$score <= -0.8)
                        return 
'Clearly Negative';
                    if(
$score < -0.1)
                        return 
'Negative';
                    if(
$score != 0)
                        return 
'Neutral';
                    return 
'Mixed';
                };
                if(
$client->debug)
                    echo 
'<pre>'HtmlSpecialChars(print_r($sentiment_analysis1)), '</pre>';
                echo 
'<h2>Results:</h2>',"\n";
                
$sentences count($sentiment_analysis->sentences);
                echo 
'<h3>Sentences: '$sentences'</h3>',"\n";
                
$score $sentiment_analysis->documentSentiment->score;
                echo 
'<p>Sentiment score: '$score' '$analyze_sentiment_score($score), '</p>',"\n";
                for(
$sentence 0$sentence $sentences; ++$sentence)
                {
                    echo 
'<h3>Sentence ', ($sentence 1), ': 'HtmlSpecialChars($sentiment_analysis->sentences[$sentence]->text->content), '</h3>';
                    
$score $sentiment_analysis->sentences[$sentence]->sentiment->score;
                    echo 
'<p>Sentiment score: '$score' '$analyze_sentiment_score($score), '</p>',"\n";
                }
        }

3.2.11 Show a form to let the user enter a text message to analyse the user sentiments

?>
<form method="POST">
<h2><?php echo HtmlSpecialChars($user->name); ?>, please enter a text to analyze:</h2>
<div>
    <textarea name="text" rows="6" cols="60"><?php
        
if(IsSet($_POST['text']))
        {
            echo 
HtmlSpecialChars($_POST['text']);
        }
?>
    </textarea>
</div>
<div>
    <input type="submit" value="Analyze">
</div>
</form>
</body>
</html>
<?php
    
}
    else
    {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>OAuth client error</title>
</head>
<body>
<h1>OAuth client error</h1>
<pre>Error: <?php echo HtmlSpecialChars($client->error); ?></pre>
</body>
</html>
<?php
    
}

?>

4. How Can You Download or Install the PHP OAuth Client Class to Call APIs Using the PHP Composer Tool

The PHP OAuth Client class can be downloaded from the package download page in zip or tar.gz format.

If you use the PHP Composer tool, you can find instructions in the package download page using the Install with Composer button to update your projects' composer.json file to install this package and any dependent packages when your project is installed or updated.




You need to be a registered user or login to post a comment

1,616,107 PHP developers registered to the PHP Classes site.
Be One of Us!

Login Immediately with your account on:



Comments:

No comments were submitted yet.



  Post a comment Post a comment   See comments See comments (0)   Trackbacks (0)  
  All package blogs All package blogs   PHP OAuth Library PHP OAuth Library   Blog PHP OAuth Library package blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Implement PHP ...