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

Member

by addison , in category: PHP General , a year ago

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

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , a year 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.

Related Threads:

How to convert a json string to an array in php?
How to save json array in mysql using php?
How to create nested array json using php?
How to create nested array json using php?
How to get update data from json file in discord.js?
How to get data from json file using name in url in react.js?