gpt4 book ai didi

javascript - 我如何解析来自 openlibrary api 的 Json 数据? (适本地)

转载 作者:可可西里 更新时间:2023-11-01 07:08:05 24 4
gpt4 key购买 nike

如果已经回答,请原谅我。我看到了关于 json 数据和 openlibrary 的各种答案

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

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

  • 对上一个问题的补充 -我想将原始数据显示为:

标题:书的瓷砖作者:本书作者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);
?>

当页面加载时显示如下:

ISBN: 0789721813 title: Red Hat Linux author: Hellums, Duane

最佳答案

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

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

curl_setopt($cURL, CURLOPT_RETURNTRANSFER, 1);

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

参见 PHP manual关于 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]);
}

关于javascript - 我如何解析来自 openlibrary api 的 Json 数据? (适本地),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31351849/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com