Access JSON from wp_remote_get in Wordpress

2019-07-23 04:11发布

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;
}

1条回答
叛逆
2楼-- · 2019-07-23 04:48

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 );
查看更多
登录 后发表回答