如何使用php json_decode()从JSON文件中提取精确值?

时间:2012-10-08 20:50:14

标签: php

    {
   "kind": "books#volume",
   "id": "a3ERAAAAYAAJ",
   "etag": "Pax/JBMS5hw",
   "selfLink": "https://www.googleapis.com/books/v1/volumes/a3ERAAAAYAAJ",
   "volumeInfo": {
    "title": "Passion-flowers",
    "authors": [
     "Julia Ward Howe"
    ],
    "publishedDate": "1854",
    "industryIdentifiers": [
     {
      "type": "OTHER",
      "identifier": "HARVARD:32044023800626"
     }
    ],
    "pageCount": 187,
    "printType": "BOOK",
    "contentVersion": "full-1.0.0",
    "imageLinks": {
     "smallThumbnail": "http://bks2.books.google.it/books?id=a3ERAAAAYAAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",
     "thumbnail": "http://bks2.books.google.it/books?id=a3ERAAAAYAAJ&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"
    },
    "language": "en",
    "previewLink": "http://books.google.it/books?id=a3ERAAAAYAAJ&printsec=frontcover&dq=flowers&as_brr=7&hl=&cd=1&source=gbs_api",
    "infoLink": "http://books.google.it/books?id=a3ERAAAAYAAJ&dq=flowers&as_brr=7&hl=&source=gbs_api",
    "canonicalVolumeLink": "http://books.google.it/books/about/Passion_flowers.html?hl=&id=a3ERAAAAYAAJ"
   },
   "saleInfo": {
    "country": "IT",
    "saleability": "FREE",
    "isEbook": true
   },
   "accessInfo": {
    "country": "IT",
    "viewability": "ALL_PAGES",
    "embeddable": true,
    "publicDomain": true,
    "textToSpeechPermission": "ALLOWED",
    "epub": {
     "isAvailable": false,
     "downloadLink": "http://books.google.it/books/download/Passion_flowers.epub?id=a3ERAAAAYAAJ&hl=&output=epub&source=gbs_api"
    },
    "pdf": {
     "isAvailable": true,
     "downloadLink": "http://books.google.it/books/download/Passion_flowers.pdf?id=a3ERAAAAYAAJ&hl=&output=pdf&sig=ACfU3U0sPdmPZp_LmFzZXatBjMeV54xJxA&source=gbs_api"
    },
    "webReaderLink": "http://books.google.it/books/reader?id=a3ERAAAAYAAJ&as_brr=7&hl=&printsec=frontcover&output=reader&source=gbs_api",
    "accessViewStatus": "FULL_PUBLIC_DOMAIN"
   }
  }

您好,我有一个Json文件,看起来像我上面发布的那篇文章。 我想提取此文件中包含的所有标题以及缩略图网址。我尝试使用此代码访问第一个标题项,但它没有成功:

<?php

$file = file_get_contents("volumes.json");

$json = json_decode($file, true);

$json->items->volumeInfo[0]->title;

?>

我得尝试在第7行获取非对象的属性。为什么我不能将$ json作为对象访问?我该怎么做才能提取所有数据?感谢

3 个答案:

答案 0 :(得分:1)

你可以尝试

$json = json_decode($file, true);
var_dump($json['volumeInfo']['title']);

或者

$json = json_decode($file);
var_dump($json->volumeInfo->title);

输出

string 'Passion-flowers' (length=15)

答案 1 :(得分:0)

问题在于您将$ json作为数组加载。如果要将其作为对象加载,您需要执行以下操作:

$json = json_decode($file, false);

http://php.net/manual/en/function.json-decode.php

答案 2 :(得分:0)

如果明确告诉json_decode()总是返回数组(第二个参数,这是好的),则不应尝试使用对象表示法访问结果中的任何内容。