How to use PHP to query the contents of a JSON array stored in a flat file and return the result?

Experts,

I have a flat file (users.php) with a JSON array stored within.

The JSON array takes the following format:
[{"name":"Sam Smith","profltitle":", MBA","location":"San Francisco","displayspecialty":"Accounting","headshotphoto":"2235396_photoweb.jpg","homepageurl":"http:\/\/example.com"},{"name":"Paula Jones","profltitle":", MA","location":"San Jose","displayspecialty":"Human Resources","headshotphoto":"2235555_photoweb.jpg","homepageurl":"http:\/\/example.com"}]

Open in new window


Users are allowed to specify a search term via a textbox:
<input name="searchfor" id="searchfor" type="text" />

Open in new window


Using the search term provided by the user I need to query the JSON array and pull results that match the given search term. The matching values need to be returned in a JSON format.

This is the programming logic as I see it now:

<?php
//DEFINE SEARCH TERM AS PROVIDED BY USER
$term = addslashes($_POST['searchfor']);
//DEFINE JSON ARRAY
$json_array = fopen('users.php');
//USING SEARCH TERM QUERY ARRAY
...
//PROVIDE THE RESULTS IN JSON FORMAT
...
?>

Any assistance would be helpful.
evibesmusicAsked:
Who is Participating?
 
gr8gonzoConsultantCommented:
First, don't use addslashes if you're going to search against the decoded array.

// Our search results
$results = array();

// JSON-decode the contents of users.php
$users = json_decode(file_get_contents("users.php"),true);

// Loop through users
foreach($users as $user)
{
  // Does the name field contain the search term?
  if(stripos($user["name"], $term) !== false)
  {
    // Yes, add user to $results
    $results[] = $user;
  }
}

// Display the JSON-encoded results
echo json_encode($results);

Open in new window

0
 
evibesmusicAuthor Commented:
@gr8gonzo:

Thank you very much. Works perfectly!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.