Sas Gabriel
Sas Gabriel

Reputation: 1556

how to read data from url

I have this code:

$json = file_get_contents('http://yiimp.ccminer.org/api/wallet?address=DshDF3zmCX9PUhafTAzxyQidwgdfLYJkBrd');
$obj = json_decode($json);
var_dump($obj);

and the object here is empty, no data available but if I access the URL from browser the result is this:

{"currency": "DCR", "unsold": 0.030825917365192, "balance": 0.02007306, "unpaid": 0.05089898, "paid24h": 0.05796425, "total": 0.10886323}

what am I missing?

Upvotes: 1

Views: 254

Answers (2)

Unamata Sanatarai
Unamata Sanatarai

Reputation: 6647

If you need to go with file_get_contents you need to set the context for the request. Apparently this URL REQUIRES to see a user-agent string in headers (cause, you know... anti-bot-secruity).

The following works:

<?php
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"User-Agent: foo\r\n"
  )
);

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('http://yiimp.ccminer.org/api/wallet?address=DshDF3zmCX9PUhafTAzxyQidwgdfLYJkBrd', false, $context);

var_dump($file);
// string(137) "{"currency": "DCR", "unsold": 0.030825917365192, "balance": 0.02007306, "unpaid": 0.05089898, "paid24h": 0.05796425, "total": 0.10886323}"

However. I Strongly suggest cURL

file_get_contents() is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter. https://stackoverflow.com/a/11064995/2119863

So please stop file_get_contents.

<?php
// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'http://yiimp.ccminer.org/api/wallet?address=DshDF3zmCX9PUhafTAzxyQidwgdfLYJkBrd',
    CURLOPT_USERAGENT => 'Sample cURL Request'
));
// Send the request & save response to $resp
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
var_dump(json_decode($resp));

and you get:

object(stdClass)#1 (6) {
  ["currency"]=>
  string(3) "DCR"
  ["unsold"]=>
  float(0.030825917365192)
  ["balance"]=>
  float(0.02007306)
  ["unpaid"]=>
  float(0.05089898)
  ["paid24h"]=>
  float(0.05796425)
  ["total"]=>
  float(0.10886323)
}

Upvotes: 2

DerJacques
DerJacques

Reputation: 332

As mentioned by others, there seems to be an issue with the API. Personally, the URL returned data on the first load but could not be reached on my next requests.

This code (with a different URL) works perfectly fine for me:

$json = file_get_contents('http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1');
$obj = json_decode($json);
print_r($obj);

Upvotes: -1

Related Questions