PHPology is a collective of highly skilled, award winning, web gurus.
Contact Raj on 07985 467 213 or email [email protected]

Posting JSON data to an API via PHP and cURL

We are working on a bespoke API platform on this "hush hush" project and rather then sending data to the API in the usual way via PHP and cURL, we changed the game a bit for when we were importing chunks of data which was uploaded in a CSV file.

Rather then looping through the CSV rows (say 1000 rows), we were not keen on making 1000 HTTP requests but instead we came to an agreement that we would break down the 1000 rows into chunks of X amount (100 say) making only 10 HTTP calls.

Now that the data was broken into chunks, we opted that the data would be sent to the API in a json format and the code explains how I did it.

Just a quick overview of the code:
1. place the rows from the CSV into an array called $csv_array
2. using array_chunk, break down the array by 10 and assign to the variable $csv_array_chunk
3. loop through $csv_array_chunk and loop through the secondary array
4. using a temporary array, take the values from the secondary array and add it into the $temp_array (I have indexed the array with email, firstname, lastname)
5. encode $temp_array into json within an index of "invitation" (the API would check against this index)
6. send the json data via cURL to the API
        you need to set the content-type via the HTTPHEADER option
7. check for a response from the API (which is in JSON)

<?php 
$csv_array_chunk = array_chunk($csv_array, 10, false);
foreach($csv_array_chunk as $chunk)
{
    $i = 0;
    $temp_array = array();
    foreach($chunk as $data)
    {
        $temp_array[$i]['email'] = $data[0];
        $temp_array[$i]['firstname'] = $data[1];
        $temp_array[$i]['lastname'] = $data[2];
        $i++;
    }
    //bespoke request to the API for this json data
    $json_data = json_encode(
        array("invitations" => $temp_array)
    );
    //bespoke request to the API for this json data
    $json_data = json_encode($temp_array);
    $url = "http://www.somewheretogo.com/api/endpoint";
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                         
        'Content-Type: application/json', 
        'Content-Length: ' . strlen($json_data))
    );
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
    $json_result = curl_exec($ch); //expecting a json response from the endpoint
    curl_close($ch);  // Seems like good practice
    //take the response which is json and encode it into an array
    $response_array = json_decode($json_result, true);
    print_r($response_array);
}
exit;
?>