-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetch_news.php
73 lines (55 loc) · 1.78 KB
/
fetch_news.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
<?php
// Establish database connection
$servername = "localhost";
$username = "YOUR_DB_USERNAME";
$password = "YOUR_DB_PASSWORD";
$dbname = "YOUR_DB_NAME";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch news from the News API
$apiKey = "YOUR_API_KEY"; // Replace with your News API key
$keyword = "India";
$newsUrl = "https://newsapi.org/v2/everything?q=" . urlencode($keyword) . '&apiKey=' . $apiKey;
if(strstr($newsUrl, '&')){
$url = str_replace('&', '&', $newsUrl);
header("Location: $newsUrl");
exit();
}
$newsResponse = file_get_contents($newsUrl);
$newsData = json_decode($newsResponse, true);
if ($newsData["status"] == "ok") {
$articles = $newsData["articles"];
// Prepare SQL statement to insert news
$insertStmt = $conn->prepare("INSERT INTO news (title, description, url) VALUES (?, ?, ?)");
// Insert new news into the database
foreach ($articles as $article) {
$title = $article["title"];
$description = $article["description"];
$url = $article["url"];
// Decode HTML entities in the URL
$url = html_entity_decode($url);
// Bind parameters to the SQL statement
$insertStmt->bind_param("sss", $title, $description, $url);
// Execute the SQL statement
$insertStmt->execute();
}
$insertStmt->close();
// Fetch news from the database
$selectQuery = "SELECT * FROM news";
$result = $conn->query($selectQuery);
$news = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$news[] = $row;
}
}
// Return news as JSON response
header('Content-Type: application/json');
echo json_encode($news);
} else {
echo "Error occurred while fetching news.";
}
$conn->close();
?>