Daily news php scrip
Here is a basic PHP script to fetch and display daily news from a news API:
Note: This script uses the News API (https://newsapi.org/) to fetch news data. You'll need to sign up for a free API key to use this script.
daily_news.php
<?php
// Set your News API key
$apiKey = 'YOUR_API_KEY_HERE';
// Set the news category (e.g. "general", "sports", "entertainment", etc.)
$category = 'general';
// Set the number of news articles to fetch
$limit = 5;
// Set the API endpoint URL
$url = 'https://newsapi.org/v2/top-headlines?category='. $category. '&apiKey='. $apiKey;
// Use cURL to fetch the API response
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
// Decode the JSON response
$data = json_decode($response, true);
// Loop through the news articles and display them
foreach ($data['articles'] as $article) {
echo '<h2>'. $article['title']. '</h2>';
echo '<p>'. $article['description']. '</p>';
echo '<a rel="nofollow" target="_blank" href="'. $article['url']. '">Read more...</a>';
echo '<br><br>';
}
?>
How it works:
- The script sets the News API key, news category, and number of news articles to fetch.
- It uses cURL to fetch the API response from the News API endpoint.
- The script decodes the JSON response using
json_decode()
. - It loops through the news articles and displays each article's title, description, and URL.
Tips and variations:
- You can customize the script to display different types of news (e.g. sports, entertainment, etc.) by changing the
category
variable. - You can also customize the script to display more or fewer news articles by changing the
limit
variable. - You can use a different API endpoint or API key if you prefer.
- You can add more features to the script, such as filtering by date or author, or displaying images or videos.
Note: This script is just a basic example and may not work as-is. You'll need to modify it to fit your specific needs and requirements. Additionally, be sure to check the News API terms of service to ensure you're using the API correctly.