> ## Documentation Index
> Fetch the complete documentation index at: https://docs.crazyrouter.com/llms.txt
> Use this file to discover all available pages before exploring further.

# PHP 示例

> PHP 调用 Crazyrouter API 示例

> 更新日期：2026-06-06

## 基础对话

```php theme={null}
<?php

$apiKey = 'sk-xxx';
$baseUrl = 'https://api.crazyrouter.com/v1';

$data = [
    'model' => 'gpt-5.5',
    'messages' => [
        ['role' => 'user', 'content' => '你好，用PHP写一个冒泡排序']
    ]
];

$ch = curl_init($baseUrl . '/chat/completions');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey,
    ],
    CURLOPT_POSTFIELDS => json_encode($data),
    CURLOPT_RETURNTRANSFER => true,
]);

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);
echo $result['choices'][0]['message']['content'];
```

## 图像编辑

```php theme={null}
<?php

$apiKey = 'sk-xxx';
$baseUrl = 'https://api.crazyrouter.com/v1';

// 使用 GPT-Image-2 编辑图片
$ch = curl_init($baseUrl . '/images/edits');

$postFields = [
    'model' => 'gpt-image-2',
    'image' => new CURLFile('original.png', 'image/png'),
    'prompt' => '把背景改成星空',
];

curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Authorization: Bearer ' . $apiKey,
    ],
    CURLOPT_POSTFIELDS => $postFields,
    CURLOPT_RETURNTRANSFER => true,
]);

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);

// gpt-image-2 通常返回 data[0].url；不要传 response_format=b64_json
$imageUrl = $result['data'][0]['url'] ?? null;
echo "图片地址: " . $imageUrl . "\n";
```

## 流式输出

```php theme={null}
<?php

$apiKey = 'sk-xxx';
$baseUrl = 'https://api.crazyrouter.com/v1';

$data = [
    'model' => 'gpt-5.5',
    'messages' => [['role' => 'user', 'content' => '讲一个笑话']],
    'stream' => true,
];

$ch = curl_init($baseUrl . '/chat/completions');
curl_setopt_array($ch, [
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => [
        'Content-Type: application/json',
        'Authorization: Bearer ' . $apiKey,
    ],
    CURLOPT_POSTFIELDS => json_encode($data),
    CURLOPT_WRITEFUNCTION => function ($ch, $data) {
        $lines = explode("\n", $data);
        foreach ($lines as $line) {
            if (str_starts_with($line, 'data: ') && $line !== 'data: [DONE]') {
                $json = json_decode(substr($line, 6), true);
                $content = $json['choices'][0]['delta']['content'] ?? '';
                echo $content;
            }
        }
        return strlen($data);
    },
]);

curl_exec($ch);
curl_close($ch);
echo "\n";
```

<Note>
  以上聊天示例默认使用 2026 年 3 月 23 日已在生产环境实测成功的 `gpt-5.5`。如果你要切换模型，优先改成同样已验证的 `claude-opus-4-8` 或 `gemini-3.1-pro`。
</Note>
