Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pull json data into php

I am trying to pull json data into a relevant php page. I have product data in json and a php page that loops through it to display the products in a list, which works fine. Clicking any of these products in the list takes me to its product detail page (by adding ?product=<? $product['name'] ?> to the url, but I cannot pull the right data into this specific page. Here is my setup:

JSON file

{"products": [
  {"name": "Banana","price": "$10"},
  {"name": "Vodka","price": "$1"}
]}

PHP for product list (works fine)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<?php
$products_json = file_get_contents('assets/json/products.json');
$decoded_json = json_decode($products_json, true);
$products = $decoded_json['products'];

foreach($products as $product) {
?>

<p><?= $product['name']; ?></p>
<a href="product-detail.php?product=<?= $product['name']; ?>'">See Details</a>

<?php }?>

PHP for product detail page, where it all goes wrong

$products_json = file_get_contents('assets/json/products.json');
$decoded_json = json_decode($products_json, true);
$product = $decoded_json['products'];

<h1>Product Name: <?= $product['name'] ?></h1>
<h1>Product Name: <?= $_GET['name'] ?></h1> //also tried this, but no luck

p.s. don’t be fooled by my reputation score – that was all from years ago and from one good answer explaining bootstrap 3!

>Solution :

$product is an array of all the products, not a single product. You need to loop over it to find the information for the product passed as the parameter.

$products_json = file_get_contents('assets/json/products.json');
$decoded_json = json_decode($products_json, true);
$products = $decoded_json['products'];
foreach ($products as $product) {
    if ($product['name'] == $_GET['product']) { ?>
        <h1>Product Name: <?= $product['name'] ?></h1>
        Price: <?= $product['price'] ?>
        <?php
        break;
    }
}

If you have lots of products, it would probably be a good idea to make the JSON an associative array where the product name is the key. Or use a database instead of a JSON file.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading