Voila , comment relever les flux rss et les enregistrer dans une db .
<?php
// ======================================
// fetch_feeds.php — Compatible PHP 5.6
// ======================================
// CONFIG BASE DE DONNÉES
$host = "";
$user = "";
$pass = "";
$dbname = "";
// Connexion MySQL
$mysqli = new mysqli($host, $user, $pass);
if ($mysqli->connect_error) die("Erreur MySQL: " . $mysqli->connect_error);
// Création de la base si inexistante
$mysqli->query("CREATE DATABASE IF NOT EXISTS `$dbname` CHARACTER SET utf8 COLLATE utf8_general_ci");
$mysqli->select_db($dbname);
// Création de la table feednews si inexistante
$createTable = "
CREATE TABLE IF NOT EXISTS feednews (
id INT AUTO_INCREMENT PRIMARY KEY,
source VARCHAR(255),
category VARCHAR(255),
title TEXT,
link TEXT,
description TEXT,
pubDate DATETIME,
date_added TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE KEY unique_entry (title(255), link(255))
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
";
$mysqli->query($createTable);
// Charger la liste des feeds
$jsonFile = __DIR__ . '/feeds.json';
if (!file_exists($jsonFile)) {
die("Fichier feeds.json manquant !");
}
$feeds = json_decode(file_get_contents($jsonFile), true);
if (!$feeds) {
die("Erreur: impossible de lire feeds.json");
}
// Fonction pour récupérer et parser un flux RSS
function fetchRSS($url) {
$context = stream_context_create(array(
'http' => array('timeout' => 10, 'user_agent' => 'Mozilla/5.0')
));
$content = @file_get_contents($url, false, $context);
if (!$content) return array();
libxml_use_internal_errors(true);
$xml = simplexml_load_string($content);
if (!$xml) return array();
$items = array();
foreach ($xml->channel->item as $item) {
$items[] = array(
'title' => trim((string)$item->title),
'link' => trim((string)$item->link),
'description' => trim(strip_tags((string)$item->description)),
'pubDate' => date('Y-m-d H:i:s', strtotime((string)$item->pubDate))
);
}
return $items;
}
// Boucle sur chaque flux
$totalAdded = 0;
foreach ($feeds as $feed) {
echo "⏳ Lecture de: {$feed['source']}...\n";
$items = fetchRSS($feed['url']);
foreach ($items as $news) {
if ($news['title'] && $news['link']) {
$stmt = $mysqli->prepare("
INSERT IGNORE INTO feednews (source, category, title, link, description, pubDate)
VALUES (?, ?, ?, ?, ?, ?)
");
$stmt->bind_param("ssssss",
$feed['source'],
$feed['category'],
$news['title'],
$news['link'],
$news['description'],
$news['pubDate']
);
$stmt->execute();
if ($stmt->affected_rows > 0) $totalAdded++;
$stmt->close();
}
}
}
echo "\n✅ Import terminé. Nouveaux articles ajoutés : $totalAdded\n";
$mysqli->close();
?>
ce script php a bessoin d’un fichier json (ref feeds.json ) a placer dans le meme repertoire:
[
{"source":"BBC News","category":"Monde général","url":"https://feeds.bbci.co.uk/news/rss.xml"},
{"source":"BBC World","category":"International","url":"https://feeds.bbci.co.uk/news/world/rss.xml"},
{"source":"Le Monde","category":"France/Monde","url":"https://www.lemonde.fr/rss/une.xml"},
{"source":"CNN","category":"US/Monde","url":"http://rss.cnn.com/rss/edition.rss"},
{"source":"The Guardian","category":"UK/Monde","url":"https://www.theguardian.com/international/rss"},
{"source":"New York Times","category":"US/Monde","url":"https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml"},
{"source":"Al Jazeera","category":"Moyen-Orient/Monde","url":"https://www.aljazeera.com/xml/rss/all.xml"},
{"source":"Associated Press","category":"Faits divers","url":"https://feedx.net/rss/ap.xml"},
{"source":"Fox News","category":"US/Conservateur","url":"http://feeds.foxnews.com/foxnews/latest"},
{"source":"TechCrunch","category":"Tech/Startups","url":"https://techcrunch.com/feed/"},
{"source":"Bloomberg","category":"Économie","url":"https://feeds.bloomberg.com/markets/news.rss"},
{"source":"France 24","category":"France/International","url":"https://www.france24.com/fr/rss"},
{"source":"DW","category":"Europe/Monde","url":"https://rss.dw.com/xml/rss_en_top.xml"}
]
placer le php en cron job pour une execution toutes les x heures .
et voici un bout de code pour voir les data
<?php
// ======================================
// news.php — Frontend d'affichage des flux RSS
// Compatible PHP 5.6
// ======================================
// CONFIG BASE DE DONNÉES
$host = "";
$user = "";
$pass = "";
$dbname = "";
// Connexion MySQL
$mysqli = new mysqli($host, $user, $pass, $dbname);
if ($mysqli->connect_error) die("Erreur MySQL: " . $mysqli->connect_error);
// Filtres (source / catégorie / recherche)
$source = isset($_GET['source']) ? trim($_GET['source']) : '';
$category = isset($_GET['category']) ? trim($_GET['category']) : '';
$search = isset($_GET['search']) ? trim($_GET['search']) : '';
// Construction de la requête SQL
$sql = "SELECT * FROM feednews WHERE 1";
$params = array();
$types = '';
if ($source != '') {
$sql .= " AND source = ?";
$params[] = $source;
$types .= 's';
}
if ($category != '') {
$sql .= " AND category = ?";
$params[] = $category;
$types .= 's';
}
if ($search != '') {
$sql .= " AND (title LIKE ? OR description LIKE ?)";
$params[] = "%$search%";
$params[] = "%$search%";
$types .= 'ss';
}
$sql .= " ORDER BY pubDate DESC LIMIT 100";
$stmt = $mysqli->prepare($sql);
if (count($params) > 0) {
$stmt->bind_param($types, ...$params);
}
$stmt->execute();
$result = $stmt->get_result();
// Récupération des filtres pour le menu déroulant
$sourcesRes = $mysqli->query("SELECT DISTINCT source FROM feednews ORDER BY source ASC");
$categoriesRes = $mysqli->query("SELECT DISTINCT category FROM feednews ORDER BY category ASC");
?>
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title>📰 Actualités globales</title>
<style>
body {
font-family: Arial, sans-serif;
background: #f7f7f7;
margin: 0; padding: 0;
}
header {
background: #333;
color: white;
padding: 15px;
text-align: center;
}
.container {
width: 90%;
max-width: 1000px;
margin: 20px auto;
background: white;
border-radius: 8px;
padding: 15px 20px;
box-shadow: 0 0 8px rgba(0,0,0,0.2);
}
form {
margin-bottom: 15px;
display: flex;
flex-wrap: wrap;
gap: 10px;
align-items: center;
}
select, input[type=text] {
padding: 8px;
border: 1px solid #ccc;
border-radius: 5px;
}
button {
padding: 8px 12px;
background: #007BFF;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
}
button:hover {
background: #0056b3;
}
.article {
border-bottom: 1px solid #ddd;
padding: 10px 0;
}
.article h3 {
margin: 0;
font-size: 18px;
}
.article p {
margin: 5px 0;
color: #555;
}
.article small {
color: #888;
}
footer {
text-align: center;
padding: 10px;
color: #888;
font-size: 13px;
}
</style>
</head>
<body>
<header>
<h1>📰 Agrégateur RSS Global</h1>
</header>
<div class="container">
<form method="get" action="">
<select name="source">
<option value="">Toutes les sources</option>
<?php while ($s = $sourcesRes->fetch_assoc()): ?>
<option value="<?= htmlspecialchars($s['source']) ?>" <?= ($s['source']==$source?'selected':'') ?>>
<?= htmlspecialchars($s['source']) ?>
</option>
<?php endwhile; ?>
</select>
<select name="category">
<option value="">Toutes les catégories</option>
<?php while ($c = $categoriesRes->fetch_assoc()): ?>
<option value="<?= htmlspecialchars($c['category']) ?>" <?= ($c['category']==$category?'selected':'') ?>>
<?= htmlspecialchars($c['category']) ?>
</option>
<?php endwhile; ?>
</select>
<input type="text" name="search" placeholder="Rechercher..." value="<?= htmlspecialchars($search) ?>">
<button type="submit">Filtrer</button>
<a href="news.php" style="margin-left:10px;color:#007BFF;text-decoration:none;">Réinitialiser</a>
</form>
<?php if ($result->num_rows == 0): ?>
<p>Aucune actualité trouvée.</p>
<?php else: ?>
<?php while ($row = $result->fetch_assoc()): ?>
<div class="article">
<h3><a href="<?= htmlspecialchars($row['link']) ?>" target="_blank"><?= htmlspecialchars($row['title']) ?></a></h3>
<p><?= htmlspecialchars(mb_strimwidth($row['description'], 0, 250, '...')) ?></p>
<small>
🗞️ <?= htmlspecialchars($row['source']) ?> —
📂 <?= htmlspecialchars($row['category']) ?> —
🕒 <?= htmlspecialchars($row['pubDate']) ?>
</small>
</div>
<?php endwhile; ?>
<?php endif; ?>
</div>
<footer>
© <?= date('Y') ?> Agrégateur RSS — Actualisation via <code>fetch_feeds.php</code>
</footer>
</body>
</html>
<?php
$stmt->close();
$mysqli->close();
?>