在 Wordpress 中从 wp_remote_get 访问 JSON [英] Access JSON from wp_remote_get in Wordpress

查看:25
本文介绍了在 Wordpress 中从 wp_remote_get 访问 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 wp_remote_get 访问从这个 Google 图书 API 请求返回的 json,但它没有输出数据.谁能告诉我是什么问题?

I'm trying to access the json that's returned from this Google books API request using wp_remote_get but its not outputting the data. Can anyone tell me what the problem is?

$request = wp_remote_get('https://books.google.com/books?bibkeys=9780001955073%2C%209780001982116%2C%209780001981768&jscmd=viewapi&callback=listisbns');

$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );

foreach( $data as $book ) {
   echo $book->info_url;
}

推荐答案

如果你使用 JavaScript 通过回调函数 listisbns 就可以了,在 PHP 中使用返回的结果你必须清理返回的字符串:

It would be ok if you were using JavaScript via the callback function listisbns, to use the returned result in PHP you gotta clean up the returned string:

$body = wp_remote_retrieve_body( $request );

# clean start removing "listisbns("
$body = str_replace( 'listisbns(', '', $body );

# clean end removing last two characters: ");"
$body = substr( $body, 0, strlen($body) - 2 );

# data ok to proceed
$data = json_decode( $body );

这篇关于在 Wordpress 中从 wp_remote_get 访问 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆