0

i'm trying to get the fields "name, price, image and rarity" to show in a php file, anyone can help me? Thanks ;D

{
  "status": 300,
  "data": {
    "date": "2019-09-16T00:00:00.000Z",
    "featured": [
      {

        "name": "Flying Saucer",
        "price": "1,200",
        "images": {
          "icon": icon.png",
        },
        "rarity": "epic",
      },

I'm using this that a friend told me, but i cant put that to work :c

<?php
$response = json_decode(file_get_contents('lista.json'), true);
foreach ($response as $val) {

    $item = $val['name'];

    echo "<b>$item</b>";
}
?>


2 Answers 2

1

I'm not quite sure what you are trying to achieve. You can just access the contents via the $response array like this:

echo $response['status']; // would output 300

You can use foreach to iterate through the array. For example: If you want to output the name of every element of the array you can use:

foreach ($response['data'] as $val) { // loop through every element of the data-array (if this makes sense depends on the structure of the json file, cant tell because it's not complete)
    echo $val['featured']['name'];
}
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much! Can i ask you how to get the images displaying? I'm trying to do <img src="<?php echo $png; ?>">
That depends on how the paths are meant to be used. The json file itself does not include the image but the name of the file which can be used to find it. Due to the fact it's only a filename you're going to need a url to add it behind. Which is depending on the context of the json file.
For example, for calling the icon.png (without link) i need to do something like Data->Featured->images ?
Just check the path in the json (how it's nested). So yeah, it would be data->featured->images->icon
0

You gotta get the index in $val['data']['featured']['name'] to retrieve the name index.

When you defined the second parameter of json_decode, you said that you want your json to be parsed to an array. The brackets in the original json identify when a new index of your parsed array will begin.

I suggest you to read about json_decode and json in general:

1 Comment

Thank you for your words ;D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.