Daily news php script
Here is a basic PHP script that fetches and displays daily news from a JSON API:
<?php
// Set API endpoint and API key
$apiEndpoint = 'https://newsapi.org/v2/top-headlines';
$apiKey = 'YOUR_API_KEY_HERE';
// Set parameters for API request
$params = array(
'country' => 'us', // or 'uk', 'ca', etc.
'category' => 'general', // or 'business', 'entertainment', etc.
'apiKey' => $apiKey
);
// Make API request
$url = $apiEndpoint. '?'. http_build_query($params);
$response = json_decode(file_get_contents($url), true);
// Display news headlines
echo '<h1>Daily News</h1>';
echo '<ul>';
foreach ($response['articles'] as $article) {
echo '<li>';
echo '<a rel="nofollow" target="_blank" href="'. $article['url']. '">'. $article['title']. '</a>';
echo '</li>';
}
echo '</ul>';
?>
This script uses the file_get_contents
function to fetch the JSON data from the API, and then decodes the JSON data using the json_decode
function. The script then loops through the array of articles and displays the title and URL of each article in an unordered list.
You'll need to replace YOUR_API_KEY_HERE
with your actual API key from the news API provider. You can obtain an API key by signing up for a free account on the news API provider's website.
You can customize this script to fit your needs by modifying the API endpoint, parameters, and display format. For example, you could add more parameters to filter the news by date range or add more fields to display in the list.
Some popular news APIs include:
- News API (https://newsapi.org/)
- Google News API (https://news.google.com/news/)
- Bing News API (https://www.bing.com/news)
Make sure to check the terms of service and usage guidelines for each API before using it in your script.