Current Location: Home> Latest Articles> PHP Tutorial: Practical Guide to Integrate Baidu Crowd Attribute Recognition API

PHP Tutorial: Practical Guide to Integrate Baidu Crowd Attribute Recognition API

gitbox 2025-08-04

Introduction

The Baidu Crowd Attribute Recognition API is a powerful tool for analyzing user attributes. It can accurately identify a user's age, gender, occupation, and interests based on multidimensional data. This article demonstrates how to quickly integrate the Baidu API using PHP, enabling developers to efficiently obtain user profiling information.

Preparation

First, apply for the “Crowd Attribute Recognition” service on the Baidu AI Open Platform and obtain your API Key and Secret Key. Log in to the platform, go to the console, find the service, and create a new application. After creation, you will receive the necessary credentials.

Installing the PHP SDK

Use Composer to install Baidu's official PHP SDK:

composer require baidu/aip-sdk

After installation, include the SDK’s autoload file in your project:

require_once 'vendor/autoload.php';

API Call Example

<?php
require_once 'vendor/autoload.php';

use BaiduAipClient;
use BaiduAipAipImageCensor;

const APP_ID = 'your_app_id';
const API_KEY = 'your_api_key';
const SECRET_KEY = 'your_secret_key';

$client = new Client(APP_ID, API_KEY, SECRET_KEY);  // Create Client object
$imageCensor = new AipImageCensor($client);       // Create AipImageCensor object

// Load image content
$image = file_get_contents('your_image_path');

// Call the Crowd Attribute Recognition API
$result = $imageCensor->user()->crowd($image);

// Handle API response
if (!empty($result['error_code'])) {
    echo 'Error: ' . $result['error_msg'];
} else {
    // Extract crowd attributes
    $attributes = $result['result']['user_attributes'][0]['attributes'];

    // Output attributes
    echo 'Age: ' . $attributes['age'] . "<br>";
    echo 'Gender: ' . $attributes['gender'] . "<br>";
    echo 'Occupation: ' . $attributes['occupation'] . "<br>";
    echo 'Interests: ' . $attributes['interest'];
}
?>

Remember to replace your_app_id, your_api_key, and your_secret_key with your actual credentials, and your_image_path with the path of the image you want to analyze.

Running the Script

Save the PHP file and run it in your terminal or command line. The script will return user attribute data such as age, gender, occupation, and interests, providing valuable insights for precise user analysis.

Conclusion

This article demonstrated how to quickly integrate Baidu’s Crowd Attribute Recognition API using PHP and the official SDK. Developers can extend this foundation to build applications such as targeted marketing and user profiling, enhancing the intelligence and user insights of their products.