首页 > 解决方案 > 使用远程get调用API

问题描述

不知道这应该放在这里还是放在 WordPress 位上,如果离题了,会放在那里 :)

我正在尝试调用 API(PHP 新手),但我完全不知道如何继续?这是我目前所拥有的......

class MyClass  {
private static $instance = null; 

protected function __construct() {
}

private function __clone() {}
private function __wakeup() {}

public static function getInstance() {
  if (self::$instance == null)  {
     self::$instance = new self;
    }     
    return self::$instance;
  } 

//Make the request
private function fetch_data($body) {
   // Do we have this information in our transients already?
  $transient = get_transient( 'fetch_data' );  

  // Yep!  Just return it and we're done.
  if( ! empty( $transient ) ) {              
    // The function will return here every time after the first time it is run, until the transient expires.
    return $transient;          
  // Nope!  We gotta make a call.
  } else { 
  $api_url = "https://someapi.co.uk/api";
  $request = wp_safe_remote_get(  $api_url );
  $body = wp_remote_retrieve_body(wp_safe_remote_get( $request ));

  // Save the API response so we only call every hour
  set_transient('fetch_data', '$body', 900);
    if( is_wp_error( $request ) ) {
      echo 'Something went wrong!';
      return false; // Bail early
    }
    else
    {
      $my_data = json_decode( $body, true );
    }   
    return $my_data;  
  }
  }
}
MyClass::getInstance();

任何帮助,将不胜感激 :)

在另一页上,我包含了类所在的文件

include(locate_template(('modules/my-api-bridge.php'), false, false));

并使用它

$my_data = MyClass::getInstance();

当我 var dump 我得到这个

object(MyClass)#3894 (0) {
}

我尝试使用这样的变量

echo $my_data['Itinary'] ['ItineraryDetails'] ['Name']

我收到此错误消息

FATAL ERROR: UNCAUGHT ERROR: CANNOT USE OBJECT OF TYPE MyClass AS ARRAY

我假设 json_decode($body, true) 会将 JSON 对象转换为 PHP 数组?

所以我尝试像这样访问对象

echo $my_data->Itinary->ItineraryDetails->Name

我收到此错误消息

Notice: Undefined property: MyClass::$Itinary in...
Notice: Trying to get property of non-object in... 
Notice: Trying to get property of non-object in...

显然有些不对劲,我看不到什么?同样,如果这更适合 WordPress 网站,那么我会在那里重新发布:)

标签: phpwordpress

解决方案


推荐阅读