如何通过php解析这个json文件?

时间:2015-12-08 15:58:20

标签: php json

我试图使用php解析这个包含我商店产品的json文件,但没有运气!我是php的新手,我尝试在线搜索,但没有任何答案。这是我的json文件的一部分:

    [
  {
    "_type": "default",
    "description": [
      "Product Description comes here"
    ],
    "url": "here is the url to my seo friendly url",
    "price": [
      "11.64"
    ],
    "sizes": [
      "sizes come here"
    ],
    "images": [
      "image name and address is here"
    ],
    "_template": "5c1333451e128f546e451197f6c6061b3a66d1ee",
    "_cached_page_id": "5119b553b1512ae1a19d6cd0d3f29e51e111a90c",
    "name": [
      "product name is here"
    ]
  },
  {
    "_type": "default",
    "description": [
      "Product #2 Description comes here"
    ],
    "url": "here is the url to my seo friendly url",
    "price": [
      "11.64"
    ],
    "sizes": [
      "sizes come here"
    ],
    "images": [
      "image name and address is here"
    ],
    "_template": "5c1333451e128f546e451197f6c6061b3a66d1ee",
    "_cached_page_id": "5119b553b1512ae1a19d6cd0d3f29e51e111a90c",
    "name": [
      "product #2 name is here"
    ]
  }
]

这只是整个json文件的一个示例,但它遵循这种格式。我尝试编写以下PHP代码来索引它,但正如我所说,没有运气:

    <?php
// this code reads from the files provided to it and populates the     database with products

$jsondata = file_get_contents("55products.json");
$json = json_decode($jsondata, true);


foreach ($json["products"] as $product)
{
    // now lets split it into smaller pieces
    foreach ($product as $product_infos) {
        print_r($product_infos);
        echo "<br /><br /><br />";


    }

}

但仍然无法访问内容或具体,我不知道如何访问那里的数据存储。我知道这可能是一个非常愚蠢的问题,但所有在线教程都没有类似的语法,所以请帮助我。 最好的问候。

1 个答案:

答案 0 :(得分:1)

内部元素本身就是数组,您需要使用索引0

来访问这些值
$obj = json_decode($json,true);
// var_dump($obj);exit;

foreach ($obj as $product)
{
    print $product["description"][0] . "<br/>";
    print $product["images"][0] . "<br/>";
    print $product["url"] . "<br/>";
    print $product["name"][0] . "<br/>";
}

将输出

Product Description comes here
image name and address is here
here is the url to my seo friendly url
product name is here
Product #2 Description comes here
image name and address is here
here is the url to my seo friendly url
product #2 name is here