Php 如何从url读取数据
我有以下代码:Php 如何从url读取数据,php,json,Php,Json,我有以下代码: $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, "bal
$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}
我错过了什么 正如其他人提到的,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);
如果需要使用
file\u get\u contents
,则需要设置请求的上下文。显然,此URL需要在标题中查看用户代理字符串(因为,您知道……反机器人安全性)
以下工作:
<?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}"
首先,你不能回显对象。当我把这个URL放到浏览器中时,我得到了一个404。可能就是这样。在PHP中,您可以在请求完成后立即查看$http\u response\u header
的值来检查服务器的响应。其次,如果运行json_decode,它会将json文本转换为PHP对象,而PHP对象通常不会正确响应。所以你必须var_dump($obj)代码>以在屏幕上查看它。或者只是echo$json
当然。@ADyson,有时候url对特定的人不起作用,对我来说它仍然起作用,但半小时前它也不起作用,过些时候再试一次不是很好。听起来服务器有问题。但无论如何,您可以按照我的建议来检查PHP代码中的响应。obj的值只是空的,即使我更改为var_dumpYeah代码也可以,因为问题不在于代码本身。。另外,这看起来不是一个答案。如果我使用另一个链接,它也对我有效,但我需要特定的链接才能工作。。。这就是为什么我还添加了linkfyi。。。我不在乎这个链接是否经常不起作用,我只需要它每天工作一次,即使我白天打更多的电话
<?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)
}