Current Path : /home/church/www/comparefloridarates.com/ |
Current File : /home/church/www/comparefloridarates.com/example.php |
<!DOCTYPE html> <html> <head> <title>API implementation example</title> <style> caption { background-color: silver; white-space: nowrap; } table { float: left; margin-right: 50px; } </style> </head> <body> <h1>API implementation example using PHP</h1> <form action="https://rate.honestpolicy.com/v2/get_rates" method="post"> <table> <caption>API input</caption> <thead> <tr> <th>Name</th> <th>Value</th> </tr> </thead> <tbody> <tr> <td>Zip</td> <td><input type="text" name="zip" /></td> </tr> <tr> <td>Dwelling Coverage Amount</td> <td><input type="text" name="cov_a" /></td> </tr> <tr> <td>Year Built</td> <td><input type="text" name="year_built" /></td> </tr> <tr> <td>Construction Type</td> <td><select name="construction_type"><option>Frame</option><option>Masonry</option></td> </tr> <tr> <td></td> <td><input type="submit" value="Get Quotes"/></td> </tr> </tbody> </table> </form> <table> <caption>Premiums output</caption> <thead> <tr> <th>Carrier</th> <th>Premium</th> </tr> </thead> <tbody> <?php # Only show results if page was called with a POST (from the input form) if( 'POST' == $_SERVER['REQUEST_METHOD'] ){ # Function that will be used to sort the results by premium price function sort_by_rate($a, $b) { if ($a['premium'] == $b['premium']) { return 0; } return ($a['premium'] < $b['premium']) ? -1 : 1; }; # Map each input into an array $postdata = http_build_query( array( 'api_key' => "6f3I3c4WJ9fQ11e38ffd78LV22tc9a66", 'zip' => $_POST["zip"], 'cov_a' => $_POST["cov_a"], 'year_built' => $_POST["year_built"], 'construction_type' => $_POST["construction_type"] ) ); # Compose HTTP POST request $opts = array('http' => array( 'method' => 'POST', 'content' => $postdata ) ); $context = stream_context_create($opts); # Place POST request $json_string = file_get_contents('https://rate.honestpolicy.com/v2/get_rates', false, $context); # Parse resulting JSON $decoded_json = json_decode($json_string, true); if($decoded_json['rates']) { # Sort the results by premium price $rates = $decoded_json['rates']; usort($rates, "sort_by_rate"); # Produce one table row per carrier/rate foreach ($rates as $rate) { echo '<tr><td>'; echo $rate['company']; echo '</td><td style="text-align: right;">$'; echo $rate['premium']; echo '</tr></td>'; } } else { # Show error messages echo '<tr><td colspan="2">'; echo $json_string; echo '</td></tr>'; } } ?> </tbody> </table> </body> </html>