文档首页/ 云搜索服务 CSS/ SDK参考/ PHP SDK调用示例
更新时间:2026-11-17 GMT+08:00
分享

PHP SDK调用示例

本文以调用CSS的查询集群列表(ListClustersDetails)接口为例,介绍华为云PHP SDK的使用方法。

前提条件

  • 已获取华为云账号对应的Access Key(AK)和Secret Access Key(SK),具体操作请参见新增访问密钥。
  • 运行SDK的环境已安装PHP 5.6及以上版本。

安装SDK

推荐通过Composer安装华为云PHP SDK。Composer是PHP的依赖管理工具,允许在项目中声明依赖关系并安装这些依赖。

在命令终端执行以下命令安装Composer和华为云PHP SDK。以3.1.203版本的PHP SDK为例,最新的SDK版本信息可通过SDK中心查看获取。

# 安装Composer。如果已安装,可跳过此命令。 
curl -sS https://getcomposer.org/installer | php 
 
# 安装PHP SDK。 
composer require huaweicloud/huaweicloud-sdk-php:3.1.203

使用SDK

以下是一个完整的PHP示例,演示如何使用华为云PHP SDK调用查询集群列表(ListClustersDetails)接口。

  • 如果需要获取其他接口的SDK示例,请参见获取SDK示例代码。
  • 本示例中仅提供了基本的接口参数配置说明,更多的进阶配置请参见SDK的用户手册。
  • 如果把认证用的AK/SK直接写到代码中会有较大的安全风险,建议在配置文件或环境变量中以密文存放AK/SK,使用时解密,确保安全。本示例中把AK和SK保存为环境变量CLOUD_SDK_AK和CLOUD_SDK_SK,具体操作请参见环境变量。
<?php
require_once "vendor/autoload.php";
use HuaweiCloud\SDK\Core\Auth\BasicCredentials;
use HuaweiCloud\SDK\Core\Http\HttpConfig;
use HuaweiCloud\SDK\Core\Exceptions\ConnectionException;
use HuaweiCloud\SDK\Core\Exceptions\RequestTimeoutException;
use HuaweiCloud\SDK\Core\Exceptions\ServiceResponseException;
use HuaweiCloud\SDK\Css\V1\CssClient;
use HuaweiCloud\SDK\Css\V1\Model\ListClustersDetailsRequest;

// The AK and SK used for authentication are hard-coded or stored in plaintext, which has great security risks. It is recommended that the AK and SK be stored in ciphertext in configuration files or environment variables and decrypted during use to ensure security.
// In this example, AK and SK are stored in environment variables for authentication. Before running this example, set environment variables CLOUD_SDK_AK and CLOUD_SDK_SK in the local environment
$ak = getenv('CLOUD_SDK_AK');
$sk = getenv('CLOUD_SDK_SK');
$endpoint = "https://css.cn-north-4.myhuaweicloud.com";
$projectId = "";
$credentials = new BasicCredentials($ak,$sk,$projectId);
$config = HttpConfig::getDefaultConfig();
$config->setIgnoreSslVerification(true);

$client = CssClient::newBuilder(new CssClient)
  ->withHttpConfig($config)
  ->withEndpoint($endpoint)
  ->withCredentials($credentials)
  ->build();
$request = new ListClustersDetailsRequest();

try {
  $response = $client->ListClustersDetails($request);
  echo "\n";
  echo $response;
} catch (ConnectionException $e) {
  $msg = $e->getMessage();
  echo "\n". $msg ."\n";
} catch (RequestTimeoutException $e) {
  $msg = $e->getMessage();
  echo "\n". $msg ."\n";
} catch (ServiceResponseException $e) {
  echo "\n";
  echo $e->getHttpStatusCode(). "\n";
  echo $e->getRequestId(). "\n";
  echo $e->getErrorCode() . "\n";
  echo $e->getErrorMsg() . "\n";
}

相关文档