110 lines
3.7 KiB
PHP
110 lines
3.7 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use Illuminate\Support\Facades\Cache;
|
|
use Illuminate\Support\Facades\Http;
|
|
|
|
class ArticleController extends Controller
|
|
{
|
|
private array $feeds = [
|
|
[
|
|
'name' => 'Kementerian Pertanian',
|
|
'url' => 'https://www.pertanian.go.id/feed/',
|
|
'logo' => null,
|
|
],
|
|
[
|
|
'name' => 'CYBEX Pertanian',
|
|
'url' => 'https://cybex.pertanian.go.id/feed',
|
|
'logo' => null,
|
|
],
|
|
[
|
|
'name' => 'Litbang Pertanian',
|
|
'url' => 'https://www.litbang.pertanian.go.id/rss/berita.xml',
|
|
'logo' => null,
|
|
],
|
|
[
|
|
'name' => 'P3GI',
|
|
'url' => 'https://p3gi.co.id/feed/',
|
|
'logo' => null,
|
|
],
|
|
];
|
|
|
|
public function fetchArticles(): array
|
|
{
|
|
return Cache::remember('rss_articles', 3600, function () {
|
|
$articles = [];
|
|
|
|
foreach ($this->feeds as $feed) {
|
|
try {
|
|
|
|
$response = Http::timeout(8)->get($feed['url']);
|
|
if (!$response->ok()) continue;
|
|
|
|
$xml = simplexml_load_string($response->body(), 'SimpleXMLElement', LIBXML_NOCDATA);
|
|
if (!$xml) continue;
|
|
|
|
$items = $xml->channel->item ?? [];
|
|
$count = 0;
|
|
|
|
foreach ($items as $item) {
|
|
if ($count >= 3) break;
|
|
|
|
// Filter keyword tebu ← TAMBAHKAN DI SINI
|
|
$keywords = ['tebu', 'gula', 'perkebunan', 'penyakit tanaman', 'pertanian'];
|
|
$title = strtolower((string) $item->title);
|
|
$desc = strtolower((string) $item->description);
|
|
$relevant = false;
|
|
foreach ($keywords as $kw) {
|
|
if (str_contains($title, $kw) || str_contains($desc, $kw)) {
|
|
$relevant = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!$relevant) continue;
|
|
|
|
// Coba ambil gambar dari enclosure atau media:content
|
|
$image = null;
|
|
|
|
// Coba ambil gambar dari enclosure atau media:content
|
|
$image = null;
|
|
if (isset($item->enclosure)) {
|
|
$image = (string) $item->enclosure->attributes()->url;
|
|
}
|
|
if (!$image) {
|
|
$ns = $item->getNamespaces(true);
|
|
if (isset($ns['media'])) {
|
|
$media = $item->children($ns['media']);
|
|
$image = (string) ($media->content->attributes()->url ?? '');
|
|
}
|
|
}
|
|
// Fallback: ekstrak gambar dari description
|
|
if (!$image) {
|
|
preg_match('/<img[^>]+src=["\']([^"\']+)["\']/', (string)$item->description, $m);
|
|
$image = $m[1] ?? null;
|
|
}
|
|
|
|
$articles[] = [
|
|
'title' => (string) $item->title,
|
|
'link' => (string) $item->link,
|
|
'date' => date('d M Y', strtotime((string) $item->pubDate)),
|
|
'source' => $feed['name'],
|
|
'logo' => $feed['logo'],
|
|
'image' => $image,
|
|
'excerpt' => strip_tags(substr((string) $item->description, 0, 120)) . '...',
|
|
];
|
|
|
|
|
|
$count++;
|
|
}
|
|
} catch (\Exception $e) {
|
|
continue;
|
|
}
|
|
}
|
|
|
|
// Acak urutan artikel
|
|
shuffle($articles);
|
|
return array_slice($articles, 0, 6);
|
|
});
|
|
}
|
|
} |