我如何解析openlibrary api中的Json数据?(正确)

ben*_*ton 5 javascript php mysql json

请原谅我是否已经回答.我已经看到关于json数据和openlibrary的各种答案

到目前为止,我从openlibrary获得的json数据和我在示例中看到的json数据似乎在格式上有所不同

我的问题是,使用php(或javascript)如何将数据导入数组或个体变量并将它们放入mysql数据库.

  • 除了上一个问题 - 我想在下面显示原始数据:

标题:书籍作者:书籍作者Isbn:Isbn数字等

然后将这些细节放入mysql数据库中

[更新2015-011-07]现在我收到了答案,我已经更新了下面的代码,以显示它应该如何.以下将从openlibrary请求json数据,它将作为字符串返回.$ url中的ISBN号仅用于测试目的,因此一定要更改它.

<?php
$url ="https://openlibrary.org/api/books?bibkeys=ISBN:0789721813&jscmd=details&format=json";

$headers = array(
    "Content-type: application/json;charset=\"utf-8\"",
    "Accept: text/xml",
    "Cache-Control: no-cache",
    "Pragma: no-cache",
    "SOAPAction: \"run\""
); 

$cURL = curl_init();

curl_setopt($cURL, CURLOPT_URL, $url);
curl_setopt($cURL, CURLOPT_HTTPGET, true);
curl_setopt($cURL, CURLOPT_HTTPHEADER, $headers);
curl_setopt($cURL, CURLOPT_RETURNTRANSFER, 1);

$result = curl_exec($cURL);

foreach (json_decode($result, true) as $book) 
 {
   printf("\nISBN: %s\ttitle: %s\tauthor: %s", $book['details']['isbn_10'][0], $book['details']['title'], $book['details']['contributions'][0]);
 }

curl_close($cURL);
?>
Run Code Online (Sandbox Code Playgroud)

加载页面时,将显示以下内容:

ISBN: 0789721813 title: Red Hat Linux author: Hellums, Duane
Run Code Online (Sandbox Code Playgroud)

Cas*_*yte 1

默认情况下,cURL自动输出传输。您的代码仅显示 json 内容,但curl_exec($cURL)如果出现错误,则返回 1 或 0,而不是 json 内容。这就是为什么你无法获取你想要的数组或对象json_decode,JSON 字符串不在$result

为了获得你想要的,你需要设置另一个 cURL 选项:

curl_setopt($cURL, CURLOPT_RETURNTRANSFER, 1);
Run Code Online (Sandbox Code Playgroud)

这样curl_exec($cURL)将以字符串形式返回传输,并且不再自动输出它。

有关 的返回值,请参阅PHP 手册curl_exec

那么你只需要使用json_decode

foreach (json_decode($result, true) as $book) {
    printf("\nISBN: %s\ttitle: %s\tauthor: %s", $book['details']['isbn_10'][0], $book['details']['title'], $book['details']['contributions'][0]);
}
Run Code Online (Sandbox Code Playgroud)