Baidu Natural Language Processing is an AI semantic technology service by Baidu, offering a variety of natural language processing features including tokenization, part-of-speech tagging, named entity recognition, sentiment analysis, dependency parsing, text classification, and deep neural network (DNN) semantic recognition.
This article demonstrates how to call Baidu's Natural Language Understanding API using PHP and efficiently parse and process the returned JSON data.
Before using Baidu Natural Language Understanding API, you need to register a Baidu Smart Cloud account and activate the required service permissions.
Steps:
After registration, log in to the Baidu Smart Cloud Console to create an application and get your API Key and Secret Key.
Process:
Before calling the API, set the relevant parameters, mainly including:
Example code:
$appId = 'your-app-id'; $appKey = 'your-app-key'; $text = 'Text data to process'; $url = 'URL of the text data'; $language = 'Chinese'; $unit = 'word';
Use PHP’s cURL library to send an HTTP request. Example code:
$ch = curl_init(); $options = array( CURLOPT_URL => 'https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer?charset=UTF-8', CURLOPT_POST => true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => array( 'Content-Type: application/json', ), CURLOPT_POSTFIELDS => json_encode(array( 'appId' => $appId, 'appKey' => $appKey, 'text' => $text, 'url' => $url, 'language' => $language, 'unit' => $unit, )), ); curl_setopt_array($ch, $options); $response = curl_exec($ch); curl_close($ch);
After a successful request, the API returns JSON data, which needs to be parsed:
$result = json_decode($response); if (!empty($result->error_code)) { echo 'Request failed: ' . $result->error_msg; } else { foreach ($result->items as $item) { echo $item->item . ' ' . $item->pos . "\n"; } }
The above code outputs each tokenized word and its part-of-speech tag to the console for further processing.
This article explained the complete process of integrating Baidu Natural Language Understanding API using PHP, including account registration, app creation, parameter configuration, request sending, and response parsing.
Developers can adjust parameters as needed in real applications to flexibly implement features like text intelligence analysis, voice interaction, and machine translation.