Nested file_get_contents / json_decode I have this code but it takes over a minute to run. I'm looking at around 400 entries being brought back for the first loop. Any ideas on how it could be improved for speed?

&lt;?php

    $context = stream_context_create(array(
        'http' =&gt; array(
            'method' =&gt; 'GET',
            'header' =&gt; "Authorization: Basic abc123\r\nContent-Type: application/json\r\n"//,'content' =&gt; json_encode($postData)
        )
    ));

    // Send the request
    $response = file_get_contents('https://localhost', FALSE, $context);

    // Check for errors
    if($response === FALSE){
        die('Error');
    }
    // Decode the response
    $responseData = json_decode($response, TRUE);

    // Print the date from the response
    foreach($responseData as $row) {
       foreach($row as $k) {
             $response = file_get_contents('https://localhost/answers'.$k['id'], FALSE, $context);
             $responseDataAns = json_decode($response, TRUE);
                 echo $responseDataAns['summary']." / ".$responseDataAns['solution']."\r\n";
       }
    }
    ?&gt;


This is the REST API I am using specifically. This is used to retrieve all answers then this to get an instance.

I want to use the REST API to list all questions, allow someone to go into a question and then update it.
It seems to me that you are making multiple requests to 'https://localhost/answers'.$k['id'] inside a loop and that you have one route for each answers, such as:

https://localhost/answers100
https://localhost/answers101
https://localhost/answers102


My suggestion is to abandon that approach and combine them into one route that can handle multiple ids.
For instance:

https://localhost/answers?id[]=100&amp;id[]=101&amp;id[]=102


Then grab the id like this:

$ids = $_GET['id'];


which is an array.
Process each id one by one and combine the result and send as JSON.
For instance:

{
    "100": {
        "summary": "",
        "solution": ""
    },
    "101": {
        "summary": "",
        "solution": ""
    },
    "102": {
        "summary": "",
        "solution": ""
    }
}


So, instead of making 400 requests, you only need to make 1 request.
Much faster.