Search words in JSON file using PHP

Asked

Viewed 55 times

0

I am creating a HTML and CSS search bar. I have the Results.json file where all user names are stored. I would like to search what the user typed in the Results.json file, is it possible to?

JSON

{
    "name1":"luis",
    "name2":"joão"
}

1 answer

2


// Essa variável pode vir de um $_POST ou de outras formas
$nomeBuscado = 'Maria';

// abre o arquivo json
$ficheiro = file_get_contents("ficheiro.json");

// converte em objeto
$data = json_decode($ficheiro);

// seta mensagem defaul
$msg = 'Não encontrado';

//percorre todos os elementos e procura pelo nomeBuscado
foreach ($data as $key => $value) {
    if($value == $nomeBuscado) {
        $msg = 'Encontrado na lista!';
    }
}

// imprime se encontrou ou não
echo $msg;

  • Would it be possible to display the found results? Not just the message that the item was found.

  • In fact, he’s checking to see if the name of the $nameBuscate variable is in json, Maria in the example above. Ali is returning a string (whether it is in the list or not), it could return a true or false. What results do you refer to?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.