Reputation: 13
So I wanted to search through a JSON file with PHP. The json link: http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json. I just put the JSON file in my webserver. Heres my script:
<?php
$query = $_GET['s'];
$terms = explode(' ', $query);
$results = array();
foreach(file('items.json') as $line) {
$found = true;
foreach($terms as $term) {
if(strpos($line, $term) == false) {
$found = false;
break;
}
}
if($found) {
$results[] = $line;
} else {
}
}
print_r($results);
The problem is it shows the WHOLE json file instead of my $query. What can i do to fix that?
Upvotes: 1
Views: 175
Reputation: 24645
You can use json_encode, array_filter and a closure (PHP 5.3+) to accomplish this.
$obj = json_decode(file_get_contents("http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json"), true);
$termStr = "ninja kiwi";
$terms = explode(" ", $termStr);
$results = array_filter($obj, function ($x) use ($terms){
foreach($terms as $term){
if (stripos($x["label"], $term) ||
stripos($x["paper_item_id"], $term))
{
return true;
}
}
return false;
});
echo json_encode($results);
Upvotes: 1