bart2puck
bart2puck

Reputation: 2522

php curl request as a foreach loop

I have a server that requires me to send a curl response to get data back about a given phone number.

$numbers = array('12345','23456','345567','45678');

 foreach ($numbers as $value)
 {
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  curl_setopt($curl, CURLOPT_USERPWD, "user:password");
  curl_setopt($curl, CURLOPT_URL, "http://server/data/user=" . $value);

  $ret = curl_exec($curl);
  $result = json_decode($ret,true);

   echo $result['someData'] . "<br>";
  curl_close($curl);
 }

my questions are: is this efficient?

is there a better way?

how can i get the echo to print to screen after each curl result, until waiting until the end of the entire script to run?

Upvotes: 2

Views: 13715

Answers (2)

You need to flush the data now and then. Try something like this

<?php
ob_start(); //Turning ON Output Buffering
$numbers = array('12345','23456','345567','45678');

 foreach ($numbers as $value)
 {
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  curl_setopt($curl, CURLOPT_USERPWD, "user:password");
  curl_setopt($curl, CURLOPT_URL, "http://server/data/user=" . $value);

  $ret = curl_exec($curl);
  $result = json_decode($ret,true);

  ob_flush();//Flush the data here
  echo $result['someData'] . "<br>";
  curl_close($curl);
 }
 ob_end_flush();

Go through all those output functions here

Upvotes: 1

hamobi
hamobi

Reputation: 8130

i think if the server you're contacting only accepts a single number then it would make sense to do it this way.

if you have access to the code on the receiving end then maybe you could serialize your array and send the whole thing over in one shot.

Upvotes: 0

Related Questions