【问题标题】:Converting from file_get_contents to wp_remote_get从 file_get_contents 转换为 wp_remote_get
【发布时间】: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'] ) 似乎破坏了脚本并且是空白的。

标签: php json wordpress


【解决方案1】:

当我查看解码的 json 时,如果看起来 $data['last_price'] 不是一个数组。所以也许你想要的是:

这个:

foreach( $data['last_price'] as $price ) {
     return $price;
}

可能是:

return $data['last_price'];

因为返回的 json 对象只是看起来是财务数据的一个数组。在第一个示例中也是如此。

【讨论】:

  • 谢谢,但是当我这样做时,它似乎破坏了脚本并且没有加载。
  • 更准确地说,控制台中会显示 500 错误。
  • 实际上,这行得通!我只需要将 true 添加到 json_decode。谢谢!
【解决方案2】:

您的 print_r( $data ) 提供了您的“stdClass 对象”,但您正在使用

print_r( $data['last_price'] );

它什么也没给你。 所以为了获取对象尝试

$test=$data->last_price;
print_r($test);

希望这会对你有所帮助。

【讨论】:

  • 这并不能解决问题中的问题,它更适合评论。请仅在问题的答案解决实际问题时添加问题的答案,并且可以提供解决问题的替代方法,而其他答案尚未涵盖。
猜你喜欢
  • 2021-12-15
  • 2011-08-01
  • 1970-01-01
  • 2014-04-15
  • 1970-01-01
  • 2014-12-16
  • 1970-01-01
  • 2021-08-18
  • 1970-01-01
相关资源
最近更新 更多