Découvrons TNTSearch, une librairie ultra simple & efficace qui permet de mettre en place en quelques minutes un moteur de recherche en PHP !
En effet, si vous avez déjà implémenté un moteur de recherche à coup de mots-clés et de LIKE en SQL, vous avez probablement été confronté à des problèmes de pertinence des résultats et/ou de rapidité : avec ce moteur de recherche, on règle les deux problèmes d'un coup ;-)
Code source :
- config.php
<?php require('./vendor/autoload.php'); /** * SQL permettant de créer la table "articles" : * create table articles (id int primary key auto_increment, title varchar(255), author varchar(255), content text, description text, imageUrl text, publishedAt datetime); */ try { $db = new PDO("mysql:host=localhost;dbname=search_engine", 'root', 'root'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(PDOException $e) { echo "Connection failed: " . $e->getMessage(); }
- import.php
<?php require('./config.php'); $apiKey = "VOTRE_CLE_API"; $categories = ['technology', 'sports', 'science', 'business', 'entertainment']; foreach ($categories as $category) { $endpoint = "https://newsapi.org/v2/top-headlines?category=$category&pageSize=100&country=fr&apiKey=$apiKey"; $response = file_get_contents($endpoint); $response = json_decode($response); var_dump($response); foreach ($response->articles as $article) { $q = $db->prepare('INSERT INTO articles (title, author, content, description, imageUrl, publishedAt) VALUES (:title, :author, :content, :description, :imageUrl, :publishedAt)'); $q->bindValue('title', $article->title); $q->bindValue('author', $article->author); $q->bindValue('content', $article->content); $q->bindValue('description', $article->description); $q->bindValue('imageUrl', $article->urlToImage); $q->bindValue('publishedAt', date("Y-m-d H:i:s", strtotime($article->publishedAt))); $q->execute(); } }
- index.php
<?php require('./config.php'); use TeamTNTTNTSearchTNTSearch; $articles = []; if (!empty($_GET['q'])) { $tnt = new TNTSearch; $tnt->loadConfig([ 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'search_engine', 'username' => 'root', 'password' => 'root', 'storage' => '.', 'stemmer' => TeamTNTTNTSearchStemmerPorterStemmer::class ]); $tnt->selectIndex("articles.index"); $searchResult = $tnt->search($_GET['q'], 10); $ids = implode(", ", $searchResult['ids']); $q = $db->query("SELECT * FROM articles WHERE id IN ($ids) ORDER BY FIELD(id, $ids)"); $q = $db->query("SELECT * FROM articles WHERE CONCAT(title, content) LIKE '%" . $_GET['q'] . "%'"); $articles = $q->fetchAll(PDO::FETCH_ASSOC); } ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Recherche</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <form method="GET"> <input type="search" placeholder="Rechercher..." name="q"> <button type="submit">OK</button> </form> <?php if ($articles): ?> <h2> Résultats<br> <small><?= $searchResult['hits'] ?> résultats en <?= $searchResult['execution_time'] ?></small> </h2> <ul> <?php foreach ($articles as $article): ?> <li> <h3>[#<?= $article['id'] ?>] <?= $article['title'] ?></h3> <?= $article['content'] ?> </li> <?php endforeach ?> </ul> <?php endif ?> </body> </html>
Votre commentaire