I am setting up an input autocomplete using jquery tokeninput plugin and XML data.
I have an XML file structured as shown:
<?xml version="1.0" encoding="UTF-8"?>
<majors>
<major program="GCIS">Computing & Info Sci (PHD)</major>
<major program="UINT">Business Administration (AAS)</major>
etc..
</majors>
I load it into PHP:
$majors = simplexml_load_file('../ajax/majors.xml');
I then want to do the following things:
-
reformat each
<major>
element into string, includingprogram
attribute- (ex:
<major program="GCIS">Computing & Info Sci (PHD)</major>
turns into stringGCIS - Computing & Info Sci (PHD)
- (ex:
- run the converted string through a filter function. The filter function checks for
strpos($convertedString, $userQuery)
and returns true/false if the user's query is present - elements which DO contain the
$userQuery
are all then encoded withjson_encode($arr)
- return JSON data.
This is the code I currently have... I can't seem to get the formatting / filtering to work correctly.
if(isset($_POST['query']) ) {
$majors = simplexml_load_file('../ajax/majors.xml');
# iterate through.
foreach ($majors as $key => $value) {
$arr = array('major' => $value['program'] . " - " . $value);
}
# filter the response using our query
$arr = array_filter($arr, 'filterArrayWithQuery');
# JSON-encode the response
$json_response = json_encode($arr);
# Return the response
return $json_response;
}
# ensures that the search query is present
function filterArrayWithQuery( $string ) {
return !strpos( $string, $query ) === false;
}
The end-result JSON output should look like this:
{"major":"GCIS - Computing & Info Sci (PHD)","major":"UINT - Business Administration (AAS)"}