0

I am using an API that gives a JSON response. If I copy that response into a 'test.txt' file and retrieve data from it - it's fine. However, if I try to @file_get_contents directly on the HTTPS url, I get a non-object.

function fetchMeasurments($url, $energyCoefficient, $filePrefix) {
    $connectionSettings = stream_context_create(array('http'=>
        array(
            'timeout' => 5
        )
    ));
$jsonData = @file_get_contents($url, false, $connectionSettings);
$obj = json_decode($jsonData);
    if( is_null($obj) ){
        echo 'null'; die();
    }else{
        echo 'not null'; die();
}

If I use test.txt - I get 'not null', but if I use the HTTPS url, I get null. Any thoughts?

Here is the JSON response:

{"overview":{"lastUpdateTime":"2014-10-27 11:03:15","lifeTimeData":{"energy":2.1047042E7,"revenue":2639.4795},"lastYearData":{"energy":2.105334E7},"lastMonthData":{"energy":1388652.8},"lastDayData":{"energy":749.25397},"currentPower":{"power":817.0}}}
GuitarMan
  • 89
  • 1
  • 10

1 Answers1

0

I think you should really consider using CURL instead of file_get_contents(). Curl has support for secure connections and you will not have problems with https.

Morover suppresion of errors is not a good idea.

Here you have tutorial how to make CURL connections with https

http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/

function getData($url)
{ 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);   
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
} 

Use this function instead of file_get_contents().

Notice this is very basic function without setting headers, error handling and certificate acceptation.

Robert
  • 19,800
  • 5
  • 55
  • 85