使用远程呼叫API

时间:2018-11-06 14:32:59

标签: php wordpress

不确定是应该在此处还是在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网站,那么我将在此重新发布它:)

0 个答案:

没有答案