Tuesday, 28 August 2018

PHP Font API does not return a result

This is my first time using accessing an API via PHP. I am trying to use data from police.uk.

Here is my PHP code:
    $lat = '52.629729';
    $long = '-1.131592';
    $date = '2013-01';

    $get = file_get_contents("http://data.police.uk/api/crimes-street/all-crime?lat=".$lat."&lng=".$long."&date=".$date);
    $json = json_decode($get, true);
    echo $json['location'];

I am not getting any response with this call (nothing is being displayed on the page).
What am I doing wrong?

Your call to the API returns something like this:
array (size=1105)
  0 =>
    array (size=9)
      'category' => string 'anti-social-behaviour' (length=21)
      'location_type' => string 'Force' (length=5)
      'location' =>
        array (size=3)
          'latitude' => string '52.626948' (length=9)
          'street' =>
            array (size=2)
              ...
          'longitude' => string '-1.112172' (length=9)
      'context' => string '' (length=0)
      'outcome_status' => null
      'persistent_id' => string '' (length=0)

In other words, there are multiple entries. Furthermore, the location info is yet another array:
array (size=3)
  'latitude' => string '52.626948' (length=9)
  'street' =>
    array (size=2)
      'id' => int 882380
      'name' => string 'On or near Cedar Road' (length=21)
  'longitude' => string '-1.112172' (length=9)

To output all locations (e.g. all street names), you could do something like the following:
foreach($json as $entry) {
    echo $entry['location']['street']['name'].'<br />';
}

Or just output the location of the first entry if you desire:
$json[0]['location']['street']['name'];

Tip: Use var_dump() on a variable to see how it is laid out.
Tip 2: Use error_reporting(E_ALL); at the top of your file to output all errors when you're developing.

0 comments:

Post a Comment