Current Location: Home> Latest Articles> How to Use PHP to Integrate Baidu Semantic Sentiment Analysis API for Text Sentiment Analysis

How to Use PHP to Integrate Baidu Semantic Sentiment Analysis API for Text Sentiment Analysis

gitbox 2025-06-14

1. What is Baidu Semantic Sentiment Analysis API?

In daily life, humans engage in a large amount of emotional communication, but it is often difficult to express these emotions accurately. Semantic sentiment analysis technology can identify the emotional tone of text, allowing computers to understand the emotional meaning of the text. Baidu's semantic sentiment analysis API can analyze Chinese text and provide results on emotional tone and sentiment polarity (positive, neutral, negative). This technology has wide applications in areas such as public opinion monitoring, product review analysis, customer service, community management, and reputation analysis.

This article will provide a detailed guide on how to use PHP to integrate Baidu's semantic sentiment analysis API for text sentiment analysis.

2. Steps to Integrate Baidu Semantic Sentiment Analysis API with PHP

2.1 Obtain API Key and Secret Key

Before using Baidu's Semantic Sentiment Analysis API, you need to apply for and obtain an API Key and Secret Key from the Baidu Developer Center. Here are the steps to get your API Key and Secret Key:

  1. Log in to the Baidu Smart Cloud Console.
  2. Go to "Artificial Intelligence" -> "Natural Language Processing", and click "Create Application".
  3. Enter the application name and description, then click "Create".
  4. In the application list, find your newly created application, click "Manage", and you will be able to access the API Key and Secret Key.

2.2 Write PHP Code

Write PHP code to send requests to Baidu's API using the curl library, and parse the returned results. Below is an example of PHP code:


// API Key and Secret Key
$app_key = 'your app key'; 
$secret_key = 'your secret key';
// Request parameters
$params = array(
    'text' => $text,           // Text to analyze
    '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));
// Full URL for the request
$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 the confidence level of the sentiment type
        echo $item['confidence'];  
    }
} else {
    echo 'Parsing error';
}
curl_close($curl);

2.3 Parse the Returned Results

The Baidu Semantic Sentiment Analysis API returns data in JSON format. We can use the json_decode() function to parse it into an array, and then extract the information we need. Specifically, we can retrieve the following:

  • sentiment (Sentiment Type): The sentiment type is a string, with possible values: negative (negative), neutral (neutral), and positive (positive).
  • confidence (Sentiment Confidence): The sentiment confidence is a floating-point number representing the accuracy of the sentiment classification, ranging from 0 to 1.

Below is an example output:


// Example output: positive 0.986

3. Conclusion

This article provides a detailed guide on how to integrate Baidu's Semantic Sentiment Analysis API with PHP. By obtaining API keys, writing PHP code, and parsing the returned JSON data, you can easily perform sentiment analysis on Chinese text. This technology has wide applications in areas such as public opinion monitoring, comment analysis, and sentiment analysis on social platforms.