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.
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:
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×tamp=%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);
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:
Example output:
// Example output: positive 0.986
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.