Home > database >  Generate dynamic html with JSON output (with php)
Generate dynamic html with JSON output (with php)

Time:03-12

I have multiple JSON files with different structures. What I want to do is to automatically display these JSON outputs with HTML.

Some of my JSON outputs are as follows: (Think of each of these as separate files and need to be processed separately)

{
  "parts": [
    {
      "@attributes": {
        "id": "part1"
      },
      "car": "Peugeot",
      "service": 5,
      "location": 2996,
      "price": "44.95",
      "date": "2000-10-01"
    },
    
... other objects
  ]
}
{
   "licenses":[
      {
         "driver":"John",
         "year":26,
         "info":null
      },
      

... other objects
   ]
}

Now, to process these files, I send the page name with GET on PHP and I want the corresponding JSON output to be printed to the screen with HTML as <span>$key</span> -> <span>$value</span>

How can I make this dynamic JSON output read event with PHP? Do I need to create a recursive function?

Because the files have different structures from each other. I hope I was able to explain my problem. Thanks already for yours help.

CodePudding user response:

I suggest the following:

  1. get required JSON file name from GET or POST, for example:

    $jsonfilename = $_GET['file'];

The above does not include any security protection! this is a separate topic, so do some research.

  1. load your json file and parse it:

    $json = file_get_contents('/path/'.$jsonfilename);

    $data = json_decode($json, true);

  2. read your json data:

    foreach ($data as $key=>$value){ echo ''.$key.' -> '.$value.''; }

CodePudding user response:

A simple example for your PARTS file:

$json = '
{
    "parts":
    [
      {
        "@attributes": {
          "id": "part1"
        },
        "car": "Peugeot",
        "service": 5,
        "location": 2996,
        "price": "44.95",
        "date": "2000-10-01"
      },
      {
        "@attributes": {
          "id": "part2"
        },
        "car": "Renault",
        "service": 8,
        "location": 3100,
        "price": "99.95",
        "date": "2022-03-01"
      }
    ]
}';

$arr = json_decode($json, true);

foreach($arr["parts"] as $part) {
    foreach($part as $k => $v){
        if($k == "@attributes")
            echo "<h1>" . $v["id"] ."</h1>";
        else
            echo "<span>$k</span> -> <span>$v</span> <br/>";
    }
}

This produces:

enter image description here

  • Related