从Wordpress中的wp_remote_get访问JSON

时间:2017-05-03 19:22:05

标签: php json wordpress

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

$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 个答案:

答案 0 :(得分:0)

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

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