Jump to content

GalenAltaiir

New Members
  • Posts

    8
  • Joined

  • Last visited

Posts posted by GalenAltaiir

  1. 8 minutes ago, requinix said:

    This

    "rows": {...}

    and this

    "rows": [{...}]

    are two distinctly different things.

    To figure out what you have to use to access something, work from the outside in.

    1  {
    2      "column-names": [
    3          "address1",
    4          "address2",
    5          "address3",
    6          "postcode",
    7          ...
    8      ],
    9      "rows": [
    10         {
    11             "address": "123, Imaginary Road",
    12             "someotherdata": dataset,
    13             ...,
    14             "postcode": "H3L L00"
    15         }
    16     ]
    17 }

    If you want the "address" on line 11 then you have to go through:
    1. The outermost thing is an object (line 1)
    2. The "rows" member is an array (line 9)
    3. The first item in that array is an object (line 10)
    4. The "address" member

    Since you told json_decode() that you want objects to be converted into arrays, then that means you:
    1. Start with the thing returned to you by json_decode(), which will be an array
    2. Get the "rows" member
    3. Get the first member, which would be the 0th
    4. Get the "address" member

    In the real world, if you have something called "rows" that is a JSON [ ] array then you probably shouldn't be using direct offsets on it (eg, 0) but rather a loop to get all the things inside it.

    Thank you! The API array is massive, so I was having a really hard time understanding it. Putting it like I did here, and having you explain it helped a lot. The code works now, and I got the result I wanted :)

  2. 19 minutes ago, requinix said:

    Where are you getting [0] from? I see "rows" and "address" and "postcode" but no 0...

    (and yes, you are formatting the JSON wrong. {} are for key/value pairs, [] are for straight lists)

    I tried different ways of accessing the "address", I tried 

    $array["rows"][0]
    $array["rows"]["address"]

    but those didn't work. I'm just not sure how to print out the specific elements from columns and rows. The API gives me the json file in that format when I print it as a string, although I see I made a mistake when recreating the string. It looks more like this - 

     

    $json_string = 
    '{
    
    "column-names":["address1","address2","address3","postcode", ...],
    "rows":
    [{"address":"123, Imaginary Road", "someotherdata": dataset, ..., "postcode":"H3L L00"
    
    }]}';

     

  3. 12 hours ago, requinix said:

    While possible to do in object form like that, it would be easier to have json_decode give you an array instead.

    $json_string = '{"name":"Jeff","age":20,"active":true,"column-names":["title1","title2"]}';
    
    $array = json_decode($json_string, true);
    printf('All done! Welcome to Homepage %s', $array["column-names"][1]);

     

    Awesome thanks, what should I do this if the json string was formatted bit more like this -
     

    $json_string = '{"column-names":["address1","address2","address3","postcode", ...],"rows":["address":"123, Imaginary Road", "someotherdata": dataset, ..., "postcode":"H3L L00"]}';

    and I wanted to print the address, and then a post code? The method you provided doesn't seem to work in that scenario (unless I'm formatting it wrong)

    printf('All done! Welcome to Homepage %s',$array["rows"][0]);

     

  4. Hi I have a json file that I called from an API into a string. But I noticed that that the name for the array was 2 words seperated with a "-", I understand that normally I'm able to access the array and print it using

    $object->ArrayName[index] but what do I do if the array if the array name contains a dash? $object->Array-Name[index] 

    I'm fairly new to PHP and a complete begginer with JSON so sorry if this is a bit confusing. I wrote some simple code to recreate the issue I have.

    Code:

    $json_string = '{"name":"Jeff","age":20,"active":true,"column-names":["title1","title2"]}';
    
    $object = json_decode($json_string);
    printf('All done! Welcome to Homepage %s',$object->"column-names"[1]);

    Output:

    Parse error: syntax error, unexpected '"column-names"' (T_CONSTANT_ENCAPSED_STRING), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in FILE_LOCATION on line 14

     

  5. 17 hours ago, ginerjm said:

    I'm guessing that by placing the result of the explode inside the array type you are creating a single element of an unexpected array.  Try this:

    $resultarray = explode(',',$result);

    That will produce the array you are expecting.  Explode produces an array naturally, no need to do a type on it.

     

    15 hours ago, Barand said:

    I get the impression that there should be 2 arrays in that data. The first 90 or so elements look like headings and the final 90 look like data. Could be there is something like a "\n" in the middle that isn't showing.

    You may need 2 explodes. The first to split the results into records and the second to split those records into fields.

    Thanks a lot for the help guys. I've got everything sorted now thanks to your tips. It went a little bit off-topic from the orignal post as I ran into a few issues, but that's all solved thanks to you lot.

     

    For the curious, yeah in the API the first 89 elements were headings, and the remainder was the data for those headings. I had 4 hours total to try this out (it was an open practice task, so asking for help on stuff like PHP or Curl is fine), so I sadly I didn't get to try out using a 2nd explode to split the array better. Instead I just ran a for loop until the midpoint, and then printed all the headings, then offsetting the other half by 89 and printing the 2nd time into a table. This worked pretty well, but a 2nd explode would have saved me some time. 

     

    Again thanks for the help :) 

  6. Okay, another progress update. I worked out how to put the data into an array. 

    	ob_start();
       	var_dump($resp);
        $result = ob_get_clean();
    
    
        $resultArray = array(explode(",",$result));
    
        print_r($resultArray[1]);

    but I'm having problems displaying specific parts of the array. When I run the bottom line of that code I get

    Notice: Undefined offset: 1 in <file_location> on <line number>

    If I remove "[1]" it displays the whole array, but I'm not sure why I can't display the specific parts

  7. 2 hours ago, maxxd said:

    You can use plain php curl, but honestly I think it'll be easier to deal with if you use Guzzle. I find it much easier, especially when dealing with passing tokens and keys and whatnot; as the docs say:

    $client = new GuzzleHttp\Client();
    $res = $client->request('GET', 'https://api.github.com/user', [
        'auth' => ['user', 'pass']
    ]);
    echo $res->getStatusCode();
    // "200"
    echo $res->getHeader('content-type')[0];
    // 'application/json; charset=utf8'
    echo $res->getBody();
    // {"type":"User"...'

    Give it a shot and come back with code if something goes weird.

    Thanks! I'll definately look into Guzzle. I actually managed to the API working using php curl, which took some reading and a curl to php curl converter (hence why i'll be sticking with that for now).

    I worked out how to search for specific address (the database contains home addresses as well as various ratings on the property like windows, walls, gas, any smart features etc.)
     

    But now I'm trying to work out how to do 2 things,

    - How do I modify the code so it only shows me relevant set of information

    - How do I take the output, and divide it so I can either put it as a table to display on a page, or to store certain strings as variables.

     

    This is the code I have at the moment:

     

    $url = "https://epc.opendatacommunities.org/api/v1/domestic/search?address=".$address."";
    
    
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    
    $headers = array(
       "Accept: text/csv",
       "Authorization: {Token}",
    );
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    
    
    $resp = curl_exec($curl);
    curl_close($curl);

    $address is just set to one address I found on the database.

    This is the output I get:

    Result: string(2572) "lmk-key,address1,address2,address3,postcode,building-reference-number,current-energy-rating,potential-energy-rating,current-energy-efficiency,potential-energy-efficiency,property-type,built-form,inspection-date,local-authority,constituency,county,lodgement-date,transaction-type,environment-impact-current,environment-impact-potential,energy-consumption-current,energy-consumption-potential,co2-emissions-current,co2-emiss-curr-per-floor-area,co2-emissions-potential,lighting-cost-current,lighting-cost-potential,heating-cost-current,heating-cost-potential,hot-water-cost-current,hot-water-cost-potential,total-floor-area,energy-tariff,mains-gas-flag,floor-level,flat-top-storey,flat-storey-count,main-heating-controls,multi-glaze-proportion,glazed-type,glazed-area,extension-count,number-habitable-rooms,number-heated-rooms,low-energy-lighting,number-open-fireplaces,hotwater-description,hot-water-energy-eff,hot-water-env-eff,floor-description,floor-energy-eff,floor-env-eff,windows-description,windows-energy-eff,windows-env-eff,walls-description,walls-energy-eff,walls-env-eff,secondheat-description,sheating-energy-eff,sheating-env-eff,roof-description,roof-energy-eff,roof-env-eff,mainheat-description,mainheat-energy-eff,mainheat-env-eff,mainheatcont-description,mainheatc-energy-eff,mainheatc-env-eff,lighting-description,lighting-energy-eff,lighting-env-eff,main-fuel,wind-turbine-count,heat-loss-corridor,unheated-corridor-length,floor-height,photo-supply,solar-water-heating-flag,mechanical-ventilation,address,local-authority-label,constituency-label,posttown,construction-age-band,lodgement-datetime,tenure,fixed-lighting-outlets-count,low-energy-fixed-light-count 1229391483952014103108154495749528,"142, Edgar Road",,,TW4 5QP,5844359278,D,C,61,73,Maisonette,End-Terrace,2014-10-30,E09000027,E14001005,Greater London Authority,2014-10-31,marketed sale,57,73,241,152,4,46,2.5,56,56,747,473,155,125,87,Single,Y,3rd,Y,,2104,100,double glazing installed during or after 2002,Normal,0,5,5,100,0,From main system,Good,Good,"Solid, no insulation (assumed)",N/A,N/A,Fully double glazed,Good,Good,"Cavity wall, as built, no insulation (assumed)",Poor,Poor,None,N/A,N/A,"Flat, limited insulation (assumed)",Very Poor,Very Poor,"Boiler and radiators, mains gas",Good,Good,Programmer and room thermostat,Average,Average,Low energy lighting in all fixed outlets,Very Good,Very Good,mains gas (not community),1,unheated corridor,5,,0,,natural,"142, Edgar Road",Richmond upon Thames,Twickenham,HOUNSLOW,England and Wales: 1967-1975,2014-10-31 08:15:44,owner-occupied,11,11 "

     

    I noticed that I can't store the string that comes out of

    var_dump($resp);

    as is, I was thinking if I can store the output as a string maybe I can slice it up and then I would have more control over what and how I can display the data to the user?

  8. Hi, I'm a learning PHP developer, and I'm trying to work out how to connect and use an API provided by my goverment to the public. 

    I have no idea how to set it up and test it, and I'm having a really hard time finding any help online.

    The documentation mentions using a "simple" cURL request but I have no idea how that works either, and I would like ideally to be able to pull the data and turn into an SQL database where I know how things work a little bit better within PHP.

    I would be really grateful if someone could explain how to connect and use this API with some simple code to get me started. There is a token, and a key involved so I would like to know how to verify myself for the API as well.

    You can find the access to the API here: https://epc.opendatacommunities.org/login
    and the documentation here: https://epc.opendatacommunities.org/docs/api/domestic

     

    Many thankss

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.