You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用cURL向同一API发起8次仅改data参数的请求并保持代码整洁?

批量发起cURL请求的整洁实现方案

问题描述

我需要使用cURL向某API发起8次请求,每次仅修改'data' => "Text"参数。原本打算直接复制8次代码,但这会导致代码混乱,并非理想方案。当前我的代码如下:

$url = 'https://www.paraphraser.io/paraphrasing-api';
$ch = curl_init($url);

$data = array(
            'key' => '526a099f61fdfdffdf8f27fa815129f87f',
            'data' => "SIGNIFICADO: Sonhar com arvores cheia de flores mostra que você precisa reavaliar suas decisões e objetivos. Você está tentando se encaixar nos ideais de outra pessoa. Talvez você esteja se esforçando demais para impressionar os outros. Você precisa trabalhar mais e por mais tempo para alcançar seus objetivos. Talvez você precisa fazer um pouco mais de esforço em relação a algum relacionamento.",
            'lang' => 'br',
            'mode' => '3',
            'style' => '0'
        );

$headers = array(
    'Content-Type: text/plain; charset=utf-8',
);

curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);

解决方案

通过封装请求函数+循环遍历文本列表的方式,可以彻底避免代码冗余,同时保持逻辑清晰。具体实现如下:

1. 封装可复用的请求函数

把重复的cURL初始化、参数设置、请求执行逻辑打包成一个函数,只需要传入动态变化的data文本即可。

2. 准备待处理的文本数组

将8个需要请求的文本统一放在一个数组中,方便后续遍历。

3. 循环执行请求

遍历文本数组,调用封装好的函数完成每次请求,同时可以统一收集所有结果。

完整优化代码

<?php
// 提取固定配置,便于统一维护
$apiUrl = 'https://www.paraphraser.io/paraphrasing-api';
$apiKey = '526a099f61fdfdffdf8f27fa815129f87f';
$fixedParams = [
    'lang' => 'br',
    'mode' => '3',
    'style' => '0'
];
$requestHeaders = [
    'Content-Type: text/plain; charset=utf-8',
];

// 封装API请求函数
function sendApiRequest($url, $key, $fixedParams, $headers, $targetText) {
    $ch = curl_init($url);
    
    // 组合固定参数和动态文本
    $postData = array_merge($fixedParams, [
        'key' => $key,
        'data' => $targetText
    ]);
    
    // 设置cURL选项
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    
    // 执行请求并返回结果
    $response = curl_exec($ch);
    curl_close($ch); // 及时释放资源
    
    return $response;
}

// 准备8个需要处理的文本列表
$textList = [
    "文本1内容",
    "文本2内容",
    "文本3内容",
    "文本4内容",
    "文本5内容",
    "文本6内容",
    "文本7内容",
    "文本8内容"
];

// 循环发起请求并收集结果
$allResponses = [];
foreach ($textList as $index => $text) {
    $response = sendApiRequest($apiUrl, $apiKey, $fixedParams, $requestHeaders, $text);
    $allResponses["请求".($index+1)] = $response;
    
    // 可选:添加延迟避免触发API速率限制
    sleep(1);
}

// 示例:打印所有请求结果
print_r($allResponses);
?>

额外说明

  • 固定配置与动态参数分离,后续修改API密钥、语言等参数只需改动一处。
  • 函数封装后,请求逻辑的调整无需重复修改多段代码,维护成本更低。
  • 可选的sleep(1)可以防止短时间内请求过于频繁,避免触发API的限流机制。

内容的提问来源于stack exchange,提问作者Prinple Vrlo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 18:31:03