Current Location: Home> Latest Articles> How to Use PHP to Connect with Baidu Sentiment Analysis API for Sentiment Analysis

How to Use PHP to Connect with Baidu Sentiment Analysis API for Sentiment Analysis

M66 2025-06-14

1. What is Baidu Sentiment Analysis API?

Human emotions are complex and hard to express precisely in text. Baidu's Sentiment Analysis API identifies the sentiment tones in text by analyzing its semantics and emotional tendencies. This allows the system to understand the sentiment implications of the text. The API performs sentiment classification of Chinese text, identifying its sentiment polarity (positive, neutral, or negative). It has applications in areas like public opinion monitoring, product reviews, customer service, community management, and more.

This article will focus on how to use PHP to integrate Baidu's Sentiment Analysis API for sentiment analysis of Chinese text.

2. Steps for Using PHP to Connect with Baidu Sentiment Analysis API

2.1. Obtain API Key and Secret Key

Before using Baidu's Sentiment Analysis API, you need to apply for and obtain the API Key and Secret Key. The steps are as follows:

  1. Log in to Baidu AI Cloud Console.
  2. Select “AI” -> “Natural Language Processing” and create an application.
  3. Fill in the application name and description, and click “Create.”
  4. In the application list, find your newly created application, click “Manage,” and you will find the API Key and Secret Key on the application details page.

2.2. Writing the PHP Code

Next, we need to write PHP code that uses the curl library to send requests to Baidu’s API and handle the returned data.


// API Key and Secret Key
$app_key = 'your app key'; 
$secret_key = 'your secret key'; 

// Request parameters
$params = array(
    'text' => $text, // Text to be analyzed
    'mode' => 0,
    'apikey' => $app_key,
    'timestamp' => time() // Current timestamp
);

// Calculate sign
$sig = md5(sprintf("apikey=%stext=%stimestamp=%s%s", $app_key, $text, time(), $secret_key));

// Complete request URL
$url = sprintf("https://api.baidu.com/rpc/2.0/nlp/v1/sentiment_classify?access_token=%s&timestamp=%s&sign=%s",
         getAccessToken($app_key, $secret_key), time(), $sig);

// Send request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_TIMEOUT, 10);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($params));

// Receive response
$output = curl_exec($curl);
$res = json_decode($output, true);

// Check results
if ($res && $res['text'] && $res['items']) {
    foreach ($res['items'] as $item) {
        // Output sentiment type
        echo $item['sentiment'];

        // Output sentiment confidence
        echo $item['confidence'];
    }
} else {
    echo 'Parsing Error';
}
curl_close($curl);

2.3. Parsing the Returned Results

The Baidu Sentiment Analysis API returns data in JSON format. We use the json_decode() function to parse it into an array, then extract the relevant information as needed.

The returned data contains the following key elements:

  • sentiment (Sentiment Type): Possible values are "negative", "neutral", and "positive".
  • confidence (Sentiment Confidence): A floating-point value representing the accuracy of the sentiment classification, ranging from 0 to 1.

Example output:


// Example output: positive 0.986

3. Conclusion

In this tutorial, we explained how to use PHP to connect to Baidu's Sentiment Analysis API, send requests, receive and parse the returned data. This solution allows you to effectively perform sentiment analysis on Chinese text and retrieve sentiment types and confidence scores, providing support for various application scenarios.