2017-08-31 53 views
1

数据我有这样的代码:如何读取URL

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

,这里的对象是空的,没有数据可用,但如果我从浏览器访问URL的结果是这样的:

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

我错过了什么?

+0

首先,当我把那个URL在浏览器中我得到了404这可能是它,你可以不回对象 – ArtOsi

+0

。在PHP中,您可以通过在请求完成后立即查看'$ http_response_header'的值来检查服务器的响应。其次,如果运行json_decode,它会将JSON文本转换为一个PHP对象,该对象通常不会正确回显。所以你必须'var_dump($ obj);'在屏幕上看到它。或者只是'echo $ json;'当然。 – ADyson

+0

@ADyson,有时这个url只是对特定的人不起作用,对我来说它仍然有效,但它在半小时前也没有工作,在一段时间内再次尝试 –

回答

2

如果你需要和你一起去需要设置请求的情况下file_get_contents。显然这个URL需要在标头中看到一个user-agent字符串(原因是,你知道... 反机器人安全性)。

以下工作:

<?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}" 

然而。我强烈建议cURL

file_get_contents()是一个简单的螺丝刀。非常适合简单的GET 请求,其中头部,HTTP请求方法,超时,cookiejar,重定向以及其他重要的事情都无关紧要。 https://stackoverflow.com/a/11064995/2119863

所以请停止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)); 

,你会得到:

所有的
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) 
} 
+0

这似乎工作!这是用户代理的价值 –

-1

正如其他人所说,API似乎存在问题。 个人而言,URL在第一次加载时返回了数据,但在下一次请求时无法到达。

此代码(使用不同的URL)工作完全正常,我:

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

是的代码是有效的,因为问题不在于代码本身。而且这看起来不像是答案。 – ArtOsi

+0

如果我使用另一个链接它也适用于我,但我需要特定的链接工作...这就是为什么我也加入了链接 –

+0

fyi ...我不在乎如果链接不工作到时候,我只需要它每天工作一次,即使我在白天拨打更多电话 –