【发布时间】:2017-09-05 00:53:43
【问题描述】:
我在将此函数从 file_get_contents 转换为 wp_remote_get 时遇到了一些麻烦,我希望能得到一些见解。这似乎我是如此接近。以下是两种情况,我的原件使用 file_get_contents 工作,第二种情况做同样的事情,但使用 wp_remote_get 并且不起作用。谁能帮我弄清楚我在搞砸什么?
case 'one':
$url = "https://api.bitfinex.com/v1/pubticker/btcusd";
$json = json_decode(file_get_contents($url), true);
$price = $json["last_price"];
return $price;
break;
case 'two':
$request = wp_remote_get( 'https://api.bitfinex.com/v1/pubticker/btcusd' );
if( is_wp_error( $request ) ) {
return false;
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
if( ! empty( $data ) ) {
foreach( $data['last_price'] as $price ) {
return $price;
}
}
break;
【问题讨论】:
-
您是否打印出 $request 中的所有这些变量以查看其中的内容?
-
'return $data' 似乎破坏了该网站。不会加载其他 PHP 元素。
-
不返回,对变量进行回显,对数组使用 print_r() 或 var_dump()。调试是你的朋友。如果变量和数组的内容不是您所期望的,那么您将找出原因。先搞清楚是什么。
-
使用 print_r( $data ) 给我 "stdClass Object ( [mid] => 0.000126245 [bid] => 0.000126 How to Ask => 0.00012649 [last_price] => 0.00012649 [low] => 0.00009097 [high] => 0.00016183 [volume] => 32064835.81619025 [timestamp] => 1504582363.108115698)" 但使用 print_r( $data['last_price'] ) 似乎破坏了脚本并且是空白的。