How can JSON be utilized effectively in conjunction with PHP for creating a search function on a website?
To create a search function on a website using JSON and PHP, you can store your data in a JSON file and use PHP to read and search through it. By decoding the JSON data into an array, you can easily loop through the data to find matches based on user input. Finally, you can display the search results on your website.
<?php
// Read JSON file
$data = file_get_contents('data.json');
// Decode JSON data into an array
$products = json_decode($data, true);
// Search keyword
$search = $_GET['search'];
// Search through the products array
$results = [];
foreach ($products as $product) {
if (stripos($product['name'], $search) !== false) {
$results[] = $product;
}
}
// Display search results
foreach ($results as $result) {
echo $result['name'] . "<br>";
}
?>