php - 使用远程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 网站,那么我会在那里重新发布:)
解决方案
推荐阅读
- excel-formula - 使用分隔符“>”提取最后一个字符串 Excel
- javascript - 如何在本机反应中使用 .reduce() 修改内部状态?
- redirect - 为什么这个 nginx 服务器重定向到错误的域?
- mysql - 使用 mysql workbench 8 访问 2007 到 mysql 迁移
- python - 与一维高斯的卷积
- jquery - Jquery - 我可以用什么代替 parent()
- php - Laravel 从关系的关系表中获取数据并选择列?
- android - 从 recyclerview 中删除所有卡片视图,然后添加新卡片视图 - 添加相同的卡片视图
- android - 如何整体滚动android recyclerView而不是基于元素的焦点?
- java - 使用java中的while循环将用户输入转换为星号之类的密码