0

Is it bad practice or will it be slower if I use curl within a foreach loop?

I'm planning on having an autocomplete input field, and the query in the input would be sent to an API call.

I'm getting an id from a certain link (ie: http://api.linke1.com/names)

foreach($json as j){

    $id = $j->id; //from http://api.linke1.com/names

    $url = "https://api.site/{$id}/photos";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    $output = curl_exec($ch);
    curl_close($ch);    

    $jsonDecode = json_decode($output);
    $results = $jsonDecode->results;
    foreach($results as $result)
    {   
            $photoURL= $result->photo->url; //from https://api.site/{$id}/photos
    }
}

So every time I type in a name, it will go into the foreach searching for an id from http://api.linke1.com/names, and then it will look for the photo url from the other link. I wanted to output a list of an array, so eventually i'll have a list of data to output showing information such as name, photo, etc...

Will this slow down dramatically because each letter typed in the input field it will run through this foreach loop. Would there be an easier way?

Thanks!

3
  • Is there no way to retrieve all of this information in a single request? As a general rule, performing expensive operations (and requesting data over the internet is definitely an expensive operation) while inside a loop is a bad idea. Commented Jan 20, 2013 at 8:08
  • The loop in your question looks superfluous. You would best optimize it, by not having the outer foreach. The inner foreach is also looking fishy, you probably want to break it in the first iteration. Apart from that, please only ask about concrete not hypothetical problems. Yes it can be wrong, however as it looks now, it does not even work. First get it to work, then optimize it. Commented Jan 20, 2013 at 8:08
  • What did you come up with? Commented Feb 21, 2013 at 12:16

1 Answer 1

1

Initialize the curl and the things that doesn't change before the loop and close it afterwards.

That will speed up the thing a little bit.

and you can use curl_multi_*, which can fetch several URLs in parallel.

https://www.php.net/manual/en/ref.curl.php

Sign up to request clarification or add additional context in comments.

3 Comments

Alternatively, he could just use file_get_contents() since it's a simple GET request.
@xbonez A curl-request is faster.
@xbonez Yup, they cover the question here: stackoverflow.com/questions/555523/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.