0

I have this task where I have to send a POST request to an external site to change and retrieve some data with PHP. This is how it works:

First I go to this site. Then with the use of Google Chrome I inspect the site, and then go to the Network tab. While having this window open I change Varmepumpe - luft til luft from INGEN to LITEN on the actual site. The name Energi now appears in the Network tab.

After I click on Energi I see the following under Headers:

General
Request URL:http://energiportalen.no/Mal/MinBolig/Energi
Request Method:POST
Status Code:200 OK
Remote Address:xxx

Response Headers
Access-Control-Allow-Origin:*
Cache-Control:private
Connection:keep-alive
Content-Length:84445
Content-Type:text/html; charset=utf-8
Date:Thu, 18 Feb 2016 08:36:39 GMT
Server:Microsoft-IIS/7.5
Via:1.1 m00180A11BB28 (squid/3.3.5)
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0
X-Cache:MISS from m00180A11BB28
X-Cache-Lookup:MISS from m00180A11BB28:3128
X-Powered-By:ASP.NET

Request Headers
Accept:application/json, text/javascript, */*; q=0.01
Accept-Encoding:gzip, deflate
Accept-Language:nb-NO,nb;q=0.8,no;q=0.6,nn;q=0.4,en-US;q=0.2,en;q=0.2
Connection:keep-alive
Content-Length:2430
Content-Type:application/json; charset=UTF-8
Cookie:ASP.NET_SessionId=e5tg3z53vbxtynib0htcsevr; _ga=GA1.2.599505589.1454574895; _gat=1
Host:energiportalen.no
Origin:http://energiportalen.no
Referer:http://energiportalen.no/Energianalyse/MinBolig/?municipality=0111&area=187&yoc=1989&type=2
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.109 Safari/537.36
X-Requested-With:XMLHttpRequest

Request Payload
Address: null
Area: 187
BNR: 0
Baths: 0
BuildingMaterial: 0
Bulb: 0
CellarIsCrawlSpace: false
CellarIsHeated: false
CellarIsIncluded: false
CellarIsToAir: false
CoordinateSystemCode: 0
CoordinateX: 41.1052127
CoordinateY: -74.0100643
DayReduction: false
Dishwasher: true
Divided: 0
DividedAsString: "Vertikaldelt"
Dryer: true
DurationBathsPerson: [4, 4, 4, 4, 4, 4]
EnergySaving: false
FNR: 0
FindOptimalInitiative: null
Floor: 0
FloorAsString: "Øverst"
FloorType: 1
FloorsAboveGround: 1
Freezers: 1
FridgeFreezers: 0
FullAddress: "Bolig i Hvaler"
GNR: 0
HasCellarFloor: true
HasRegisteredCellarFloors: false
HeatCapacity: 0
HeatDisribution: 0
HeatingSystem1: 0
HeatingSystem2: 0
HeatingSystem3: 0
HeatingSystem4: 0
HeatingSystem5: 0
HeatingSystem6: 0
HeatingSystem7: 0
HeatingSystem8: 0
HeatingSystem9: 0
HeatingSystem10: 0
HeatingSystem11: 0
HeatingSystem12: 0
HeatingSystem13: 0
HeatingSystem14: 0
HeatingSystem15: 0
HeatingSystem16: 0
HeatingSystem17: 0
HeatingSystem18: 0
HeatingSystem19: 0
HeatingSystem20: 0
HeatingSystem21: 0
HeatingSystem22: 0
HeatingSystem23: 0
HeatingSystem24: 0
HeatingSystem25: 0
HeatingSystemsText: null
HousingId: 0
HousingType: 2
HousingTypeAsString: "Enebolig"
Id: null
IlluminationSources: 20
InfiltrationCondition: 0
IsNewHousing: false
Letter: null
MissingAddress: true
MissingArea: false
MissingHousingType: false
MissingLocation: true
MissingMunicipality: false
MissingYearOfConstruction: false
MunicipalityName: "Hvaler"
MunicipalityNo: 111
NightReduction: false
NumHoursIllumination: 15
NumShowersPerPersonPerWeek: [6, 6, 6, 6, 6, 6]
PartHeatedArea: 0.86
Persons: 4
Placement: 0
PlacementAsString: "Ende"
PostalCode: "0000"
PostalName: ""
PresentWindowUverdi: null
PriceCoke: 0.5
PriceElectricity: 0.9
PriceGas: 1
PriceHeating: 0.8
PriceOil: 0.8
PricePellets: 0.65
PriceWood: 0.5
RatingColor: null
RatingScale: null
Refrigerators: 1
Roof: 2
RoofType: 0
RoofTypeAsString: "Ikke angitt"
SNR: 0
Street: null
StreetNumber: null
TemperatureInsideColdZone: 10
TemperatureInsideWarmZone: 21
Throughout: false
UpgradedSum: null
UpgradedSumUnit: 0
UpgradedWindowUverdi: null
Ventilation: 1
WallThickness: 0
WallType: 0
WallTypeAsString: "Ikke angitt"
WashingMachine: true
WindowChangedYear: 1989
WindowType: 0
WindowTypeAsString: "Ikke angitt"
YearOfConstruction: 1989
initiatives: ["1"]
  0: "1"

Under Request Payload there are a ton of energy related parameters that are used to calculate energy savings and similar stuff for a house. You can change the area, change the year it was built, change heating systems that are used, and so on. How do I change these paramters with a POST request in PHP, in order to send them in for recalculation so I can retrieve the information in the Preview tab under Network as JSON from an external site?

Here's an example of the Preview tab:

CO2Emissions: "380"
energy: {,…}
energyConsumption: "2 881"
energyCost: "2 592"
energyCostAsString: "kr 2 592"
lifetimeCO2Emissions: "11 400"
lifetimeEnergyConsumption: "86 430"
lifetimeSavings: 77760
liftetimeEnergyCostAsString: "kr 77 760"
optimalInitiativeId: "-1"
presentCO2Emissions: "2 343"
presentEnergy: {,…}
presentEnergyConsumption: "24 338"
presentEnergyCost: "21 904"
presentEnergyCostAsString: "kr 21 904"
presentEnergyCostSummary: "..."
presentEnergyRatingImage: "D_5.png"
recommendedInitiativeIds: []
saving: 2592
savingsAsString: "kr 2 592"
tek10Energy: {,…}
upgradedEnergyCostSummary: "..."
upgradedEnergyRatingImage: "C_4.png"

I would like to retrieve this data as JSON, but seeing as this data is changed by the values under Request Payload I also have to be able to send a request with new values in Request Payload in order to retrieve the wanted JSON result.

Here what I've tried so far, code taken mostly from this link.

$url = 'http://energiportalen.no/Energianalyse/MinBolig/?municipality=0111&area=187&yoc=1989&type=2';
$data = array('Area' => '199', 'initiatives' => '["1"]');

// use key 'http' even if you send the request to https://...
$options = array(
    'http' => array(
        'header'  => "Content-type: application/json\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    ),
);
$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
if ($result === FALSE) { /* Handle error */ }

var_dump($result);

The result from this is bool(false), as it is probably wrong code.

I assumed I had to change 'header' => "Content-type: application/x-www-form-urlencoded\r\n", to application/json as this is what I saw under Request Headers in the Network tab. I really don't have any idea if this is correct.

I also added

$data = array('Area' => '199', 'initiatives' => '["1"]');

I wanted the line of code above to change the Area and Initiatives settings under Request Payload so that I could retrieve new values under the Preview in Network.

So my question is:

How can I send parameters with a POST request to this URL and retrieve the data that is located under Network > Energi > Preview in Chrome as a JSON result with an external site.

I'm located on a separate website and I want to retrieve this data.

Is this even possible? Any help is appreciated.

Community
  • 1
  • 1
dansan
  • 194
  • 2
  • 2
  • 15

1 Answers1

0

I think what you're asking for is a PHP method that will post to a service that outputs JSON.

This can be done in PHP, with the help of curl. Sample function:

/*
    post data to a service url that returns JSON
    $urlAbs  absolute path of the service
    $data    data to post to the service
*/
function postToService_php( $urlAbs, $data ) {
    $dataJSON = json_encode($data);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $urlAbs);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($ch, CURLOPT_POSTFIELDS, $dataJSON);                                                                  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                      
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(                                                                          
        'Content-Type: application/json',                                                                                
        'Content-Length: ' . strlen($dataJSON))                                                                       
    );
    $resultJSON = curl_exec($ch);
    return $resultJSON;
}
terrymorse
  • 6,771
  • 1
  • 21
  • 27