dryb38654 2018-11-06 14:32
浏览 39

使用远程get来调用API

Not sure if this should go here or on the WordPress bit, will post it there if it's off topic :)

I'm trying to call an API (PHP newbie) and I'm completely stuck on how to proceed?? This is what I have so far...

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();

Any help would be appreciated :)

On another page I include the file where the class is

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

and use this

$my_data = MyClass::getInstance();

When I var dump I get this back

object(MyClass)#3894 (0) {
}

I try and use the variable like this

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

I get this error message

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

I assumed that json_decode($body, true) would convert the JSON object to a PHP array?

So I try and access the object like this

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

I get this error message

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

Something is obviously amiss and I can't see what? Again, if this is more suited to the WordPress site then I'll repost it there :)

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
    • ¥500 火焰左右视图、视差(基于双目相机)
    • ¥100 set_link_state
    • ¥15 虚幻5 UE美术毛发渲染
    • ¥15 CVRP 图论 物流运输优化
    • ¥15 Tableau online 嵌入ppt失败
    • ¥100 支付宝网页转账系统不识别账号
    • ¥15 基于单片机的靶位控制系统
    • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)