简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM