How to print the data in the array of json file in php?

Member

by addison , in category: PHP General , 5 months ago

How to print the data in the array of json file in php?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 5 months ago

@addison 

To print the data in the array of a JSON file in PHP, you can follow these steps:

  1. Read the JSON file using the file_get_contents() function and store it in a variable.
1
$jsonData = file_get_contents('data.json');


  1. Convert the JSON string to an associative array using the json_decode() function.
1
$data = json_decode($jsonData, true);


  1. Iterate through the array using a loop (e.g., foreach or for) and access the data you want to print.
1
2
3
4
5
6
foreach ($data as $item) {
    echo $item['property1'];
    echo $item['property2'];
    // Add more properties as needed
    echo "<br>";
}


Note: Modify property1, property2, etc. according to the actual keys/names of the properties you want to print from the JSON data.

  1. Optionally, you can format the output for better readability. For example, you can wrap each item in a div or provide line breaks.
1
2
3
4
5
6
7
foreach ($data as $item) {
   echo '<div>';
   echo 'Property 1: ' . $item['property1'] . '<br>';
   echo 'Property 2: ' . $item['property2'] . '<br>';
   // Add more properties as needed
   echo '</div><br>';
}


That's it! The data in the array of the JSON file will be printed in PHP.