Search code examples
phpcurlphp-curl

How to make multiple cURL requests to the same URL?


I need to make 8 requests to an API using cURL, each request will only change the 'data' => " Text " parameter, I thought of simply replicating the code 8 times, but that doesn't seem like a good solution and can make my code very messy .

Currently my code is like this:


$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ê precise 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);

How could I make 8 requests and leave my code clean?


Solution

  • Put your code inside a function loop through data value inside a foreach.

    foreach ($datas as $data) {
    curlAPI($data);
    }
    
    
    function curlAPI($data) {
    $url = 'https://www.paraphraser.io/paraphrasing-api';
    $ch = curl_init($url);
    
    
    
    $data = array(
                'key' => '526a099f61fdfdffdf8f27fa815129f87f',
                'data' => $data,
                '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);
    
    return $result;
    }