How to setup a basic cURL service (example with AJAX)

November 12, 2018

Great mother of cURL! It’s a post about cURL! These are hopefully some helpful ramblings to get started in the world of service generation. In this example, the user sends a name to the service, and the service returns rows from a CSV that references that name. Let’s get started.

PHP

Getting connected

In this example, the file is protected behind a HTTPAUTH, so we need to provide the correct credentials to retrieve the file’s contents located in a csv file called filename.csv

<?php 
/********************
  CONNECTION INFO
********************/ 
$CSV_FILENAME = "filename.csv";
$CSV_URL = "https://example.com/path/".$CSV_FILENAME;
$CSV_HTTP_AUTH_USERNAME = "username";
$CSV_HTTP_AUTH_PASSWORD = "password";

/********************
  GET CSV DATA
********************/ 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$CSV_URL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$CSV_HTTP_AUTH_USERNAME:$CSV_HTTP_AUTH_PASSWORD");
$result = curl_exec($ch);
curl_close($ch); 
?>

CSV example = turn data into a useable array

At the moment, we just have the entire contents of the file saved in a php variable named $result. To manipulate the data, we need to turn this into an array. The first row of the CSV is the header row, so we’ll take those values and use them as keys for the rest of the data.

<?php
/********************
  TURN CSV TO ARRAY
********************/ 
$csv_obj = [];
$csv_data = str_getcsv($result,"\n\r");
//creates a copy of csv header array
$csv_header = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $csv_data[0]);
$csv_header = str_getcsv($csv_header,",");
//removes the header from $csv_data since no longer needed
unset($csv_data[0]);
foreach($csv_data as $row){
    $csv_row = str_getcsv($row,",");
    if(count($csv_row)>1){
      $row = array_combine($csv_header, $csv_row);// adds header to each row as key
      $csv_obj[] = $row;
    }
}
?>

How to search your results

now that we have an array, we can perform a search using array_filter. The key of the user property we’ll do a search on will be “First_Name”. Note: I’m using strtolower because in my CSV, I wanted my search to not be case-sensitive.

<?php 
/********************
  APPLY FILTERS
********************/ 
$name = isset($_GET['name'])?strtoupper($_GET['name']):"";
$response_obj = searchForName($csv_obj,$name);

function searchForName($array, $name) {
    $name = strtolower($name);
    $searchResult = array_filter($array, function ($var) use ($name,$state) {
        $fname = strtolower($var['First_Name']);
        return ($fname === $name);
    });
    return $searchResult;
}
?>

Print Results as encoded JSON

Because the following AJAX request is expecting a JSON object, we’ll need to print out the data to send back in a JSON format.

<?php 
/********************
  JSON RESPONSE
********************/ 
$response=[];
$response['success'] = true;
$response['response'] = $response_obj;
echo json_encode($response);
?>

Javascript

How to call the cURL service with ajax

Using the service we created above, let’s search the CSV for a user named Charles.
*curl.php is the file with all the php code from above.

<script>
var searchdata = new Object();
searchdata.name = "Charles";
$.ajax({
	type: "GET",
	url: "curl.php",
	contentType: "application/json",
	dataType: 'json',
	data: searchdata,
	success: function (data) {
		lookupList = data.response;
		console.log(lookupList); 
	}, 
	error: function (data) { 
		alert("there was an error!");
	} 
});
</script>

Stay in Touch!

Subscribe to our newsletter.

Solutions Architecture

browse through our blog articles

Blog Archive