Home > Blockchain >  pull json data into php
pull json data into php

Time:04-30

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)

<?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!

CodePudding user response:

$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.

CodePudding user response:

When you are in the product_detail page, you can get the variable using:

$_GET["product"]

since in the previous page, you are sending it using this:

?product=<?= $product['name']; ?>

This is a key-value parameter, the right side of the = sign is the name of the variable and the left side is the value.

If you want to find the complete product based on the json file, you could filter the $products variable like this:

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

$product = array_filter($products, function($p) {
  return $p['name'] == $_GET["name"];
});

With that being said, I would suggest adding an id key to the products array, so it is easier to find it and you don't have to deal with spaces in the url.

  • Related