Current Location: Home> Latest Articles> Quick Guide to Integrate Baidu Language Sentiment Analysis API with PHP

Quick Guide to Integrate Baidu Language Sentiment Analysis API with PHP

M66 2025-06-22

What is Language Sentiment Analysis and Its Applications

Language sentiment analysis is a technology used to identify and judge the emotional tendency expressed in text. It is commonly used to understand users' attitudes and emotions towards certain topics. Baidu offers a powerful language sentiment analysis API. This article will guide you step-by-step to integrate it using PHP to achieve intelligent sentiment analysis on text.

Register a Baidu Developer Account and Create an Application

First, register an account on Baidu Developer Platform and create a new application. When creating the app, select the "Natural Language Processing" module and enable the "Language Sentiment Analysis" feature.

Obtain API Key and Secret Key

After creating the application, you can get the API Key and Secret Key from the console. These two keys are required to call the API, so keep them safe and do not disclose them.

Install Baidu PHP SDK

Baidu provides an official PHP SDK which can be installed quickly using Composer. Run the following command in your project root directory:
composer require baidu-aip/baidu-aip-sdk
After installation, include the SDK in your code:
require_once 'vendor/autoload.php';
use BaiduAIPAipNlp;

Initialize the AipNlp Client

Initialize the client by passing your appId, apiKey, and secretKey, for example:
$appId = 'your_app_id';
$apiKey = 'your_api_key';
$secretKey = 'your_secret_key';
<p>$client = new AipNlp($appId, $apiKey, $secretKey);<br>

Call the Sentiment Analysis API

Prepare your text and call the `sentimentClassify` method to analyze sentiment:
$text = 'I feel very happy today';
$result = $client->sentimentClassify($text);
<p>print_r($result);<br>

The API returns an associative array including the sentiment classification and confidence score for the input text.

Complete Sample Code

Here is the full PHP example code:
<?php
require_once 'vendor/autoload.php';
use BaiduAIPAipNlp;
<p>$appId = 'your_app_id';<br>
$apiKey = 'your_api_key';<br>
$secretKey = 'your_secret_key';</p>
<p>$client = new AipNlp($appId, $apiKey, $secretKey);</p>
<p>$text = 'I feel very happy today';<br>
$result = $client->sentimentClassify($text);</p>
<p>print_r($result);<br>
?><br>

Summary

This article introduced the full process of integrating Baidu's language sentiment analysis API with PHP, including developer account registration, API key retrieval, SDK installation, and calling the API. This helps developers easily implement text sentiment analysis features. Leveraging Baidu's powerful natural language processing capabilities can enhance your applications and improve user experience. Baidu also provides a rich set of NLP APIs, which developers can explore according to their needs.