How to convert json to html using php?

Member

by dedrick , in category: PHP General , 4 months ago

How to convert json to html using php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 4 months ago

@dedrick 

To convert JSON to HTML using PHP, you can follow these steps:

  1. Fetch the JSON data from a file, a database, or an API.
  2. Decode the JSON data using the json_decode() function to convert it into a PHP object or associative array.
  3. Create an HTML template with the desired structure.
  4. Traverse through the decoded JSON data and populate the HTML template with the corresponding values.
  5. Generate the final HTML output by combining the HTML template with the populated values.


Here's an example code that demonstrates the above steps:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
// 1. Fetch the JSON data
$jsonData = '{
  "name": "John Doe",
  "email": "[email protected]",
  "age": 25,
  "address": {
    "street": "123 Main St",
    "city": "New York",
    "state": "NY"
  },
  "hobbies": ["reading", "coding", "traveling"]
}';

// 2. Decode the JSON data
$decodedData = json_decode($jsonData);

// 3. Create an HTML template
$htmlTemplate = '
<div>
  <h2>Name: {name}</h2>
  <p>Email: {email}</p>
  <p>Age: {age}</p>
  <p>Address: {address.street}, {address.city}, {address.state}</p>
  <p>Hobbies: {hobbies}</p>
</div>';

// 4. Traverse through the decoded JSON data and populate the HTML template
$populatedTemplate = $htmlTemplate;
foreach ($decodedData as $key => $value) {
    if (is_array($value)) {
        $value = implode(', ', $value);
    }
    $populatedTemplate = str_replace('{'.$key.'}', $value, $populatedTemplate);
}

// 5. Generate the final HTML output
echo $populatedTemplate;
?>


In the example above, we are manually providing the JSON data as a string, but you can replace it with your preferred method of obtaining JSON data. The example JSON data contains a person's information, including their name, email, age, address, and hobbies.


The HTML template has placeholders like {name}, {email}, etc., which will be replaced with the corresponding values from the decoded JSON data. The str_replace() function is used to perform this replacement.


After populating the HTML template, the final HTML output is generated using the echo statement.


Please note that this example assumes a simple JSON structure. If the JSON structure is more complex or nested, you may need to modify the code accordingly.