如何使用PHP将json信息解析为html并创建<a> items with <img/> inside

时间:2016-09-29 23:34:42

标签: php html json

i try to get an info from json file to create a list of items but im not sure whats going on, because don't display the info.

here is HTML/PHP code:

<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/6e69d9a3b8.css">
    <title>List Items</title>
</head>
<body>
    <h1>List Items</h1>
    <div class="container">
        <?php
        $data = file_get_contents("test.json");
        $data = json_decode($data, true);
        echo "<pre>";
        print_r($data);
        echo "</pre>";

        echo $data[1]["href"];

        ?>
        <a href="<?php echo $data['href']?>">
            <img src="<?php echo $data['img']?>" alt="">
            <span><?php echo $data['title']?></span>
        </a>
    </div>
</body>
</html>

And this is the json content:

{
"items": [
    {
        "href": "item1",
        "img": "http://thumbnails.vaughnsoft.com/item1.png",
        "title": "Item Title 1"
    },
    {
        "href": "item2",
        "img": "http://thumbnails.mysite.com/item2.png",
        "title": "Item Title 2"
    },
    {
        "href": "item3",
        "img": "http://thumbnails.mysite.com/item3.png",
        "title": "Item Title 3"
    },
    {
        "href": "item4",
        "img": "http://thumbnails.mysite.com/item4.png",
        "title": "Item Title 4"
    }
]

}

so i know that im need an foreach to call all items but i can't display the first i any one can help me to get this data i would apreciate.

i try to do this foreach but doesn't work:

foreach($data as $key => $val) {
            echo $data['items'][0]["href"];
            echo $data['items'][0]["img"];
            echo $data['items'][0]["title"];
            echo "<br>";
            echo "<br>";
            echo $val['href'];
        }

0 个答案:

没有答案