PHP Example

SAPI endpoints can easily be called from a PHP script.

Prerequisites

In order for this example to work, you will need:

Tip: It is possible to access SAPI through an HTTP proxy, but it is not covered here. See the PHP documentation for more information.

Basic Example

The following example calls the Search endpoint and prints the name and primaryAddress.addressLine fields for each listing returned in the first page of results.

example.php

<?php

    function search($query, $location) {

        # put your API key here
        $apikey = "...";

        # location of the search API endpoint
        $endpoint = "http://api.sensis.com.au/v1/test/search";

        # construct a URL with the query string, escaping any special characters.
        $url = $endpoint . "?key=" . $apikey . 
                "&query=" . urlencode($query) . 
                "&location=" . urlencode($location);

        # call the endpoint
        $response = file_get_contents($url); 
        
        # ensure we actually got a response back         
        if (!$response) {
            throw new Exception("Error calling API ($http_response_header[0])");
        }

        # convert the response message to an associative array
        $result = json_decode($response, true);
 
        # grab the response code
        $code = $result["code"];

        # ensure successful status code
        if ($code == 200) { # success
            return $result; 
        } else {
            throw new Exception("API returned error: " . 
                    $result["message"] . ", code: " . $result["code"]);
        }

    }

    function example() {

        try {

            # perform a search for 'hairdresser' 
            $results = search("hairdresser", "st kilda, vic");
            
            echo "Total results found: " . $results["totalResults"] . "\n";

            # the results member is an array containing each listings as a nested associative array
            foreach ($results["results"] as &$result) {
                echo $result["name"] . " (" . $result["primaryAddress"]["addressLine"] . ")\n";
            }
        
        } catch (Exception $e) {
        
            # something bad happened
            echo "Internal error: $e\n";

        }

    }

    example();

?>