Save external API calls in WordPress

Mark,

I’ve had to do something similar for multiple jobs. This is a larger topic but I’ll try break it down in steps and hopefully gets you going in the right direction.

I’ve broken the code into steps and outlined them here:

if (isset($_POST['submit'])) {
    $example = $_REQUEST['example'];
    $result  = $customcontact->lookupByName( $example );
    /** API PHP Library */

    $save_data                      = array(); //step 1
    $key                            = time(); //step 2
    $save_data[ $key ]['epoch']     = $key; //step 3
    $save_data[ $key ]['timestamp'] = date( 'Y-m-d H:i:s' ); //step 4
    $save_data[ $key ]['data']      = $result; //step 5

    $existing_log = maybe_unserialize( get_option( 'my_site_option_saved_data' ) ); //step 6

    $existing_log[] = $save_data; //step 7

    update_option( 'my_site_option_saved_data', maybe_serialize( $existing_log ) ); //step 8
}
  1. Once we have the data, create a new array.
  2. Grab a unique value (in this case, epoch time). This becomes the array key for this entry into your “log”.
  3. Add the epoch time to the array as a record of when the API call was made (For more information on epoch time: https://en.wikipedia.org/wiki/Unix_time)
  4. Add a human-readable date and time to the array. I’m using a format that is friendly to SQL queries in case you need to do something to sort or query data.
  5. Add your API results to the array.
  6. We now have all the data inside the array. We go out to the database and grab the existing logged data and attempt to unserialize it (translate from database entry to array).
  7. Once we have an array of existing data, we can add a new array into it, which is our new data.
  8. Finally, we re-serialize the data and save it to the database.

A few notes:

  1. This isn’t super efficient. There would be a better way, but if you need this for testing it will work.
  2. When getting the data out, look at step 6. I’m getting the data using get_option and unserializing it (converting it to an array) via maybe_unserialize.

This should get you started. Let me know if you have any questions.

Tom

EDIT

Here are the links to the WordPress functions I’m using in my answer:

Here are a few additional links to more general logging discussion and software you can use on the server-side.