class Public_Holidays_API { //illustrates communication with the webservery public holidays API. //provides a workable wrapper class, if you don't mind my shonky coding //email me if you want any help, or want to help me - scott@webservery.com
public $status; //holds the status of the last executed command. 200 indicates succes. public $error_description; // if status <> 200 there will probably be a clue in this variable
public function __construct($email,$password) { $this->authenticating_user_email = $email; $this->authenticating_user_password = $password;
} public function __destruct() { //nothing to do really }
private function _fetch_xml_response($post_array) {
//The parameter $post_array is converted to a string of urlencoded name-value pairs and then unset($url_encoded_post_array); foreach($post_array as $key => $value) { $url_encoded_post_array[$key] = urlencode($key)."=".urlencode($value); } $nvp_string = join("&",$url_encoded_post_array);
//send to the API using curl $ch = curl_init(); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 30); curl_setopt($ch, CURLOPT_URL, "https://www.webservery.com/services/public_holidays/listener.php"); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $nvp_string); curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); curl_setopt($ch, CURLOPT_USERAGENT, "WebserveryPublicHolidaysWrapper/1.0 (+https://www.webservery.com)"); curl_setopt($ch, CURLOPT_HTTPHEADER, array( "Accept: text/xml, application/xml, text/plain, */*", "Content-Type: application/x-www-form-urlencoded", "Connection: close" )); $xml_string = curl_exec($ch); $curl_errno = curl_errno($ch); $curl_error = curl_error($ch); $curl_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE); $curl_content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE); if(!$xml_string){ $xml_string = "<?xml version='1.0' encoding='ISO-8859-1'?> <response> <b0>500</b0> <b1>The API returned no data. It shouldn't do that. It's probably unwell.</b1> </response>"; }
// Some server setups prepend warnings/notices before XML; strip to the response envelope if needed. $candidate_xml_string = $xml_string; $response_start = strpos($candidate_xml_string, "<response>"); $response_end = strpos($candidate_xml_string, "</response>"); if ($response_start !== false && $response_end !== false && $response_end > $response_start) { $candidate_xml_string = "<?xml version='1.0' encoding='ISO-8859-1'?>" . substr($candidate_xml_string, $response_start, ($response_end - $response_start) + strlen("</response>")); }