We’ve learned how to create individual profiles and how to parse CCB API XML response in our latest tutorials.
Next, we’ll learn how to search for individuals using the CCB CPI. Of course, coming from someone who has master this tutorial, searching for individuals via the CCB API is quite simple.
We’ll build upon the lessons and takeaways you’ve learned up until now. This tutorial will guide and instruct you as I show you how to build a reusable PHP/CURL function for sending (POST) and receiving (GET) data. We’ll cover the function a bit later.
But if you’re ready to get started, then so am I! Let’s start…
Prepping the essential variables
As we’ve done before in previous tutorials, create a PHP file to work within. Today’s file will be name search-individuals.php.
As you have discovered from previous tutorials, variables are very much the lifeline of any php code or application you’ll create. They make the code more manageable in the event you need to make a change. Instead of changing code 100 different places, you essentially change the variable. One time, one place, and it propagates throughout the application.
So, let’s create a churchdomain, apiUsername, apiPassword and baseAPIUrl. We’ve used each of these variables with the exception of baseAPIUrl. Going forward, you’ll want to always make sure you include a baseAPIUrl variable, so that you don’t have to concern yourself with remembering a long URL address and having to repetitiously typing it throughout your applications. In short, using the baseAPIUrl variable will save you time. Just trust me on this one.
Continuing right ahead, the baseAPIUrl variable is the url address to your CCB application’s API. You’ll notice that the baseAPIUrl is comprised of the churchdomain variable. It also allows you to send data known as a POST method and receive data known as a GET method.
<?PHP $churchdomain = 'example'; // your domain without the .com $apiUsername = 'ccbapiuser'; // your CCB api username $apiPassword = 'p@55w0rd!'; // your CCB api password $baseAPIUrl = 'https://'.$churchdomain.'.ccbchurch.com/api.php'; // base CCB API URL ?>
Setting API Service and Service Details
Moving right along, we’re not ready to set our apiService variable and the urlData variable that contains our service details. Since we’re searching for individuals, you’ll set the apiService variable to use the individual_search API service.
Although there are numerous search fields we could used to find individuals using the CCB API (i.e., first name, last name, phone, email, address, city, state, zip – see CCB API Documentation for full list of searchable parameters), we’ll narrow our selection for this tutorial to search for the last name Brown. As shown below, set the lastname variable to Brown.
Next, you’ll prepare the urlData variable, passing and binding the apiService and lastname variables to their respective key fields of srv and last_name as an array using the array_filter php function without a callback.
The array_filter function is use to remove empty or null values from an array. We don’t want to pass key fields with no data to CCB API. For one, it doesn’t make sense to send empty variables, and secondly, it just don’t make sense. 🙂 Simply put, if there is not a thing to send, then don’t send.
<?PHP $apiService = 'individual_search'; // CCB api service $lastname = 'Brown'; // sample field to search for (See CCB API documentation for more $apiService fields) $urlData = array_filter( array( 'srv' => "$apiService", 'last_name' => "$lastname" ) ); ?>
Time for a bit of functional magic
Ok, so I told you when we began this tutorial that I would introduce you to functions and why you should start using them ASAP. Functions will make your life easier.
Think of a function as something equivalent to a cookie cutter. If you had to make star cookies by hand, it would take you forever to create 100 star cookies as opposed to having a pre-cut star design to use to create the same 100 star cookies. Well, that’s what creating a function will do for you.
There are two types of functions: built in and user defined. We’ve used a few built in functions along the way. But for this tutorial we’ll create our first user-defined function. This function is going to help save you time, keystrokes and make for a much more easy and manageable codebase. So let’s get started with the creation of our PHP/CURL function for sending and receiving data using the CCB API.
First, when creating a user-defined function, you’ll want to start or declare the function using… wait for it… function. Afterwards, add a space after function and give your function a ver descriptive name. Function names can contain letters and underscores, but should never contain numbers. A function can also accept or be passed a wide number of arguments to be used within the function itself much like variables.
I’m not going to go into great detail about function as there are numerous websites to read from and on more about PHP User-Defined Functions.
For this tutorial, we’ll create a xml_response variable and set it equal to our function ccbDetails, passing it the urlData variable as the first argument and a second argument of either post or get. For now, set the second argument to get. When working with the various CCB API services, you’ll have to review the API documentation to know when to use post or get when making calls. Now that your xml_response variable is set, let’s construct your ccbDetails function, and assign it paramdata and posttype arguments as shown below.
<?PHP $xml_response = ccbDetails($urlData,'get'); // ccbDetails function to post to and get data from CCB using PHP/CURL function ccbDetails($paramdata,$posttype){ // function logic will go here } ?>
Continuing on, we are now ready to focus on the logic within the ccbDetails function now that we have set a variable using our ccbDetails function, and passed to it the urlData variable as the first argument and the ‘get’ string as the second argument.
To be able to make a successful CCB API call, we’ll need to access variables outside of our function. Variables that are set inside functions are known as local variables while variables outside of the function are global variables. We’ll need to access global variables apiUsername, apiPassword and baseAPIUrl.
In addition, we’ll add a little error checking into the function to ensure that the global variables are set before we begin trying to move the world to find and search for individuals. If any of the global variables are empty, the function will stop and die, rendering the following error message via web browser to alert the user: “Error: CCB API details missing.”.
Next, we’ll clean our paramdata variable one more time using array_filter function and reset the paramdata variable to itself. Input data can never be too clean, and coding 101 says to never blindly accept anything from the client browser as the truth! 🙂
Afterwards, we are now ready to set the query_string variable, and build the encoded web URL string using the http_build_query function with the paramdata variable as the argument.
Now you’re ready to create the url variable for when using a CCB API service that uses the get method to retrieve, concatenating the baseAPIUrl to a ? string and then to the query_string variable. If making a CCB API call using a post method, you’ll see a php if statement to account for the posttype being equal to post. When this happens, we create a different url variable that only concatenates the baseAPIUrl to a ? string, and not the query_string.
<?PHP $xml_response = ccbDetails($urlData,'get'); // ccbDetails function to post to and get data from CCB using PHP/CURL function ccbDetails($paramdata,$posttype){ // set global variables global $apiUsername, $apiPassword, $baseAPIUrl; // set error checking of global variables. if any are empty, die on the spot and display error message to web browser if (!$apiUsername || !$apiPassword || !$baseAPIUrl) die('Error: CCB API details missing.'); // reset our paramdata variable after we clean it using array_filter $paramdata = array_filter($paramdata); // remember http_build_query, well it's back $query_string = http_build_query($paramdata); // this is the get url variable consisting of baseAPIUrl, ?, and our data fields built as an URL encoded string $url = $baseAPIUrl.'?'.$query_string; // this statement will replace the url variable if the second argument posttype is set to post if($posttype == 'post') $url = $baseAPIUrl.'?'; } ?>
For the next part of the ccbDetails function we’ve created, I’m not going to give great detail on it other than to say that you’ll need to read up on php curl and the curl_setopt options.
In short, we’re now ready to take the appropriate get or post url variable, make a PHP/CURL call comprised of curl_init(), curl_setopt() and curl_exec() options, and set a response_object variable equal to the PHP/CURL return content. Finally, end the function with a return statement that returns the response_object variable.
<?PHP $xml_response = ccbDetails($urlData,'get'); // ccbDetails function to post to and get data from CCB using PHP/CURL function ccbDetails($paramdata,$posttype){ // set global variables global $apiUsername, $apiPassword, $baseAPIUrl; // set error checking of global variables. if any are empty, die on the spot and display error message to web browser if (!$apiUsername || !$apiPassword || !$baseAPIUrl) die('Error: CCB API details missing.'); // reset our paramdata variable after we clean it using array_filter $paramdata = array_filter($paramdata); // remember http_build_query, well it's back $query_string = http_build_query($paramdata); // this is the get url variable consisting of baseAPIUrl, ?, and our data fields built as an URL encoded string $url = $baseAPIUrl.'?'.$query_string; // this statement will replace the url variable if the second argument posttype is set to post if($posttype == 'post') $url = $baseAPIUrl.'?'; // set get header value to array 0 $query_header = array('0'); // when making a post call, you'll need to set the $query_header array with Accept, Connection and Content-type Headers if($posttype == 'post'){ $query_header[] =array(); $query_header[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg'; $query_header[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8'; $query_header[] = 'Connection: Keep-Alive'; } // Read up more on the curl_setopt options here: // now we're ready to initiate the curl call using the $ch variable $ch = curl_init(); // basic authentication curl_setopt($ch,CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // and don't forget that we need user credentials when making a CCB API call using PHP/CURL curl_setopt($ch,CURLOPT_USERPWD, $apiUsername . ':' . $apiPassword); // simply return the transfer as a string when set to one curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); // set CURLOPT_CONNECTTIMEOUT to 5 seconds to wait before trying to reconnect curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5); // since CCB API using https, we set the CURLOPT_PORT to 443 curl_setopt($ch,CURLOPT_PORT, 443); // don't verify ssl certificate curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0); // do verify ssl common hostname match curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,2); // we set the CURLOPT_URL using the $url variable created in previous steps curl_setopt($ch,CURLOPT_URL,$url); // header for either get or post curl_setopt($ch, CURLOPT_HTTPHEADER, $query_header); // if posttype is post, set the CURLOPT_POST to true using 1 if($posttype == 'post') curl_setopt($ch,CURLOPT_POST,1); // if posttype is post, set the CURLOPT_POSTFIELDS using the $query_string variable if($posttype == 'post') curl_setopt($ch,CURLOPT_POSTFIELDS, $query_string); // now we're ready to execute the $ch variable and return the content $content = curl_exec($ch); // not really needed, but I just like setting/returning a different variable $response_object = $content; // time to close the connection to free up resources curl_close($ch); return $response_object; } ?>
Congratulations! You now have created your first PHP user-defined function: ccbDetails. But we’re not done. We have a few more lines of code to complete and wrap up this tutorial up with a pretty red bow.
Before we started and completed the ccbDetails function, we last set the xml_response variable, so we’ll pick back up at that point to head towards the finish line.
The xml_response variable needs to be transformed to XML using SimpleXMLElement. Set the rss variable for XML transformation. If you were to print or echo the rss variable, the XML structure of the data return when we search for individuals with the last name equal to Brown would look like the following example below.
I changed the individual attribute from id to age. Don’t forget to change ‘age’ to ‘id’. CCB API does not return the age. I only used ‘age’ as an example.
For the sake of space, I’ve truncated the transformed XML response structure a bit, removing a good bit of the fields.
<?xml version="1.0" encoding="UTF-8"?> <ccb_api> <request> <parameters> <argument value="individual_search" name="srv"/> <argument value="Brown" name="last_name"/> </parameters> </request> <response> <service>individual_search</service> <service_action>execute</service_action> <availability>public</availability> <individuals count="4"> <individual age="34"> <first_name>Alvin</first_name> <last_name>Brown</last_name> <full_name>Alvin Brown</full_name> </individual> <individual age="31"> <first_name>Mallary</first_name> <last_name>Brown</last_name> <full_name>Mallary Brown</full_name> </individual> <individual age="1"> <first_name>Ian</first_name> <last_name>Brown</last_name> <full_name>Ian Brown</full_name> </individual> <individual age="0"> <first_name>Seth</first_name> <last_name>Brown</last_name> <full_name>Seth Brown</full_name> </individual> </individuals> </response> </ccb_api>
We’re now ready to parse the XML response using an XPATH query and foreach statement to return a bulleted list of individuals with their full names and age in parenthesis.
- Alvin Brown (34)
- Mallary Brown (31)
- Ian Brown (1)
- Seth Brown (0)
<?PHP $xml_response = ccbDetails($urlData,'get'); $rss = new SimpleXMLElement($xml_response); // transform to XML $nodes = $rss->xpath('//individuals/individual'); // xpath for individuals->individual foreach ($nodes as $node) { echo $node->full_name.' ('.$node['age'].')'."<br/>"; // now print the person's full name and age (See CCB API documentation for more $apiService fields) } ?>
And that’s it! You’ve made it to the end of this tutorial that taught you how to search for individuals using the CCB API. Now let’s piece together all of the codebase in its entirety into your search-individuals.php file, so that you can go test your newly found technical prowess.
<?PHP $churchdomain = 'example'; // your domain without the .com $apiUsername = 'ccbapiuser'; // your CCB api username $apiPassword = 'p@55w0rd!'; // your CCB api password $baseAPIUrl = 'https://'.$churchdomain.'.ccbchurch.com/api.php'; // base CCB API URL $apiService = 'individual_search'; // CCB api service $lastname = 'Brown'; // sample field to search for (See CCB API documentation for more $apiService fields) $urlData = array_filter( array( 'srv' => "$apiService", 'last_name' => "$lastname" ) ); $xml_response = ccbDetails($urlData,'get'); $rss = new SimpleXMLElement($xml_response); // transform to XML $nodes = $rss->xpath('//individuals/individual'); // xpath for individuals->individual foreach ($nodes as $node) { echo $node->full_name.' ('.$node['age'].')'."<br/>"; // now print the person's full name and age (See CCB API documentation for more $apiService fields) } // ccbDetails function to post to and get data from CCB using PHP/CURL function ccbDetails($paramdata,$posttype){ // set global variables global $apiUsername, $apiPassword, $baseAPIUrl; // set error checking of global variables. if any are empty, die on the spot and display error message to web browser if (!$apiUsername || !$apiPassword || !$baseAPIUrl) die('Error: CCB API details missing.'); // reset our paramdata variable after we clean it using array_filter $paramdata = array_filter($paramdata); // remember http_build_query, well it's back $query_string = http_build_query($paramdata); // this is the get url variable consisting of baseAPIUrl, ?, and our data fields built as an URL encoded string $url = $baseAPIUrl.'?'.$query_string; // this statement will replace the url variable if the second argument posttype is set to post if($posttype == 'post') $url = $baseAPIUrl.'?'; // set get header value to array 0 $query_header = array('0'); // when making a post call, you'll need to set the $query_header array with Accept, Connection and Content-type Headers if($posttype == 'post'){ $query_header[] =array(); $query_header[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg'; $query_header[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8'; $query_header[] = 'Connection: Keep-Alive'; } // Read up more on the curl_setopt options here: // now we're ready to initiate the curl call using the $ch variable $ch = curl_init(); // basic authentication curl_setopt($ch,CURLOPT_HTTPAUTH, CURLAUTH_BASIC); // and don't forget that we need user credentials when making a CCB API call using PHP/CURL curl_setopt($ch,CURLOPT_USERPWD, $apiUsername . ':' . $apiPassword); // simply return the transfer as a string when set to one curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); // set CURLOPT_CONNECTTIMEOUT to 5 seconds to wait before trying to reconnect curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,5); // since CCB API using https, we set the CURLOPT_PORT to 443 curl_setopt($ch,CURLOPT_PORT, 443); // don't verify ssl certificate curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0); // do verify ssl common hostname match curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,2); // we set the CURLOPT_URL using the $url variable created in previous steps curl_setopt($ch,CURLOPT_URL,$url); // header for either get or post curl_setopt($ch, CURLOPT_HTTPHEADER, $query_header); // if posttype is post, set the CURLOPT_POST to true using 1 if($posttype == 'post') curl_setopt($ch,CURLOPT_POST,1); // if posttype is post, set the CURLOPT_POSTFIELDS using the $query_string variable if($posttype == 'post') curl_setopt($ch,CURLOPT_POSTFIELDS, $query_string); // now we're ready to execute the $ch variable and return the content $content = curl_exec($ch); // not really needed, but I just like setting/returning a different variable $response_object = $content; // time to close the connection to free up resources curl_close($ch); return $response_object; } ?>
This has been a very intense tutorial, and hats off to those of you who have made it this far, and have been able to execute the tutorial code and view live data from your CCB.
By the way, I deem this tutorial as the long way to grandma’s house. 🙂 Yes, there is an easier and more effective method that doesn’t consume hundreds of lines of code.
In upcoming tutorials, I’ll show you how to bypass most of this codebase, condensing it to only a few lines of code. But for the sake of the various types of CCB API projects you may find yourself encountering, I wanted you to get familiar with a few additional PHP concepts. Well, that’s it for now! Cheers!