skip to Main Content

I’m new to API calls and have limited PHP / JSON knowledge.
I’m trying to retrieve UK mp details via an API call. Using (https://members-api.parliament.uk/index.html) and API call, I’m looking to get the full title of my MP.

https://members-api.parliament.uk/api/Location/Constituency/Search?searchText=KY11%201NF&skip=0&take=20

I have the code below. Using a callAPI function, the call works. I’m struggling with retrieving the data from the JSON file. I’ve tried looping through the response array and can’t get the attribute I’m looking for, which is the "nameFullTitle."

var_dump returns all the data, so the call is working; it’s more about finding the data from the JSON file that I’m struggling with.

function callAPI($method, $url, $data)
{
    $curl = curl_init();
    switch ($method) {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            if ($data) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
            break;
        default:
            if ($data) {
                $url = sprintf("%s?%s", $url, http_build_query($data));
            }
            echo $url;
            echo '<br>';
    }
    // OPTIONS:
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
        'APIKEY: 111111111111111111111',
        'Content-Type: application/json',
    ));
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    // EXECUTE:
    $result = curl_exec($curl);
    if (!$result) {
        die("Connection Failure");
    }
    curl_close($curl);
    echo 'complete';
    return $result;
}
$url = 'https://members-api.parliament.uk/api/Location/Constituency/Search?searchText=KY11%201NF&skip=0&take=20';
$get_data = callAPI('GET', $url, false);
echo '<br>';
$response = json_decode($get_data, true);
$errors = $response['response']['errors'];
$data = $response['response']['items']['id'][0];
echo $response;
foreach ($response as $x1) {
  echo "$x1 x1<br>";
    foreach ($x1 as $x2) {
        echo "$x2 x2<br>";
            foreach ($x2 as $x3){
                echo "$x3 x3<br>";
            }
        }
}
echo '<br><br>';
echo var_dump(json_decode($get_data));
echo '<br>';
echo 'check data is next row<br>';
echo $data. 'this is the data';
echo $errors;
?>

I have tried the below to loop through the array and get the data attribute looking for.

$url = 'https://members-api.parliament.uk/api/Location/Constituency/Search?searchText=KY11%201NF&skip=0&take=20';
$get_data = callAPI('GET', $url, false);
echo '<br>';
$response = json_decode($get_data, true);
$errors = $response['response']['errors'];
$data = $response['response']['items']['id'][0];
echo $response;
foreach ($response as $x1) {
    echo "$x1 x1<br>";
    foreach ($x1 as $x2) {
        echo "$x2 x2<br>";
        foreach ($x2 as $x3) {
            echo "$x3 x3<br>";
        }
    }
}
echo '<br><br>';
echo var_dump(json_decode($get_data));
echo '<br>';
echo 'check data is next row<br>';
echo $data.'this is the data';
echo $errors;

2

Answers


  1. Ignoring the curl code used to return the response and concentrating on processing the returned data itself (assuming that the curl code does return data )

    It is easier and quicker to use Object notation to access properties within the returned data than array syntax (imo) – hence not supplying true as second argument to json_decode

    # convert string response into usable JSON object
    $json=json_decode( $response );
    
    # looking into the structure you want to process the "items" node and everything within
    $items=$json->items;
    
    # The "items" node is an array of "objects" - use a "foreach" to iterate through each item if more than 1
    foreach( $items as $obj ){
        # access properties of each child Object using arrow notation (it is an object)
        $con=$obj->value;
        $id=$con->id;
        $constituency=$con->name;
        
        # each individual child elelment of the parent object is also an object so
        # you can use arrow notation to access deeper levels
        $member=$con->currentRepresentation->member->value;
        
        # using above object to access desired "nameFullTitle" value etc
        $title=$member->nameFullTitle;
        $party=$member->latestParty->name;
        
        
        # do something with recovered data
        printf('<div>Name:%s, Party:%s, Constituency:%s</div>',$title,$party,$constituency);
    }
    

    Choosing a different postcode and hence constituency yielded json as follows:

    stdClass Object
    (
        [items] => Array
            (
                [0] => stdClass Object
                    (
                        [value] => stdClass Object
                            (
                                [id] => 59
                                [name] => Angus
                                [startDate] => 2005-04-05T00:00:00
                                [endDate] => 
                                [currentRepresentation] => stdClass Object
                                    (
                                        [member] => stdClass Object
                                            (
                                                [value] => stdClass Object
                                                    (
                                                        [id] => 4736
                                                        [nameListAs] => Doogan, Dave
                                                        [nameDisplayAs] => Dave Doogan
                                                        [nameFullTitle] => Dave Doogan MP
                                                        [nameAddressAs] => 
                                                        [latestParty] => stdClass Object
                                                            (
                                                                [id] => 29
                                                                [name] => Scottish National Party
                                                                [abbreviation] => SNP
                                                                [backgroundColour] => fcf28f
                                                                [foregroundColour] => 000000
                                                                [isLordsMainParty] => 
                                                                [isLordsSpiritualParty] => 
                                                                [governmentType] => 
                                                                [isIndependentParty] => 
                                                            )
    
                                                        [gender] => M
                                                        [latestHouseMembership] => stdClass Object
                                                            (
                                                                [membershipFrom] => Angus
                                                                [membershipFromId] => 59
                                                                [house] => 1
                                                                [membershipStartDate] => 2019-12-12T00:00:00
                                                                [membershipEndDate] => 
                                                                [membershipEndReason] => 
                                                                [membershipEndReasonNotes] => 
                                                                [membershipEndReasonId] => 
                                                                [membershipStatus] => stdClass Object
                                                                    (
                                                                        [statusIsActive] => 1
                                                                        [statusDescription] => Current Member
                                                                        [statusNotes] => 
                                                                        [statusId] => 0
                                                                        [status] => 0
                                                                        [statusStartDate] => 2019-12-12T00:00:00
                                                                    )
    
                                                            )
    
                                                        [thumbnailUrl] => https://members-api.parliament.uk/api/Members/4736/Thumbnail
                                                    )
    
                                                [links] => Array
                                                    (
                                                        [0] => stdClass Object
                                                            (
                                                                [rel] => self
                                                                [href] => /Members/4736
                                                                [method] => GET
                                                            )
    
                                                        [1] => stdClass Object
                                                            (
                                                                [rel] => overview
                                                                [href] => /Members/4736
                                                                [method] => GET
                                                            )
    
                                                        [2] => stdClass Object
                                                            (
                                                                [rel] => synopsis
                                                                [href] => /Members/4736/Synopsis
                                                                [method] => GET
                                                            )
    
                                                        [3] => stdClass Object
                                                            (
                                                                [rel] => contactInformation
                                                                [href] => /Members/4736/Contact
                                                                [method] => GET
                                                            )
    
                                                    )
    
                                            )
    
                                        [representation] => stdClass Object
                                            (
                                                [membershipFrom] => Angus
                                                [membershipFromId] => 59
                                                [house] => 1
                                                [membershipStartDate] => 2019-12-12T00:00:00
                                                [membershipEndDate] => 
                                                [membershipEndReason] => 
                                                [membershipEndReasonNotes] => 
                                                [membershipEndReasonId] => 
                                                [membershipStatus] => 
                                            )
    
                                    )
    
                            )
    
                        [links] => Array
                            (
                                [0] => stdClass Object
                                    (
                                        [rel] => self
                                        [href] => /Constituency/59/Angus
                                        [method] => GET
                                    )
    
                            )
    
                    )
    
            )
    
        [totalResults] => 1
        [resultContext] => Result(s) were found based on the postcode dd8 1xf.
        [skip] => 0
        [take] => 20
        [links] => Array
            (
                [0] => stdClass Object
                    (
                        [rel] => self
                        [href] => /Constituency/Search?skip=0&take=20
                        [method] => GET
                    )
    
                [1] => stdClass Object
                    (
                        [rel] => page.next
                        [href] => /Constituency/Search?skip=0&take=20
                        [method] => GET
                    )
    
                [2] => stdClass Object
                    (
                        [rel] => page.previous
                        [href] => /Constituency/Search?skip=0&take=20
                        [method] => GET
                    )
    
            )
    
    )
    

    Which, when processed as above, yielded:

    Name:Dave Doogan MP, Party:Scottish National Party, Constituency:Angus
    
    Login or Signup to reply.
  2. please find below the code

    $url = 'https://members-api.parliament.uk/api/Location/Constituency/Search?searchText=KY11%201NF&skip=0&take=20';
    $get_data = callAPI('GET', $url, false);
    echo '<br>';
        $response = json_decode($get_data, true);
        $errors = $response['response']['errors'];
        if (empty($errors)) {
            $name_lists = array();
            if ($response) {
                foreach ($response["items"] as $item) {
                    $nameFullTitle = $item["value"]["currentRepresentation"]["member"]["value"]["nameFullTitle"];
                    $name_lists[] = $nameFullTitle;
                }
        
                echo "<pre>";
                print_r($name_lists);
                echo "</pre>";
            } else {
                echo "invalid response not valid json";
            }
        } else {
            echo "api error " . $errors;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search