Fetch news feed from social media script in php
Here is an example of a PHP script that fetches a news feed from a social media platform (in this case, Twitter):
<?php
// Set your Twitter API credentials
$consumer_key = 'YOUR_CONSUMER_KEY';
$consumer_secret = 'YOUR_CONSUMER_SECRET';
$access_token = 'YOUR_ACCESS_TOKEN';
$access_token_secret = 'YOUR_ACCESS_TOKEN_SECRET';
// Set the Twitter API endpoint and parameters
$endpoint = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$params = array(
'screen_name' => 'twitter', // Replace with the username of the account you want to fetch
'count' => 10, // Number of tweets to fetch
'include_rts' => 1, // Include retweets
'exclude_replies' => 1 // Exclude replies
);
// Set the curl options
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, 'Your App Name');
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '. $access_token,
'Content-Type: application/json'
));
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
// Execute the curl request
$response = curl_exec($ch);
curl_close($ch);
// Decode the JSON response
$tweets = json_decode($response, true);
// Loop through the tweets and print the text and timestamp
foreach ($tweets as $tweet) {
echo $tweet['text']. ' ('. $tweet['created_at']. ')'. PHP_EOL;
}
?>
This script uses the Twitter API to fetch the latest 10 tweets from the specified account, including retweets and excluding replies. It then decodes the JSON response and prints the text and timestamp of each tweet.
You'll need to replace the YOUR_CONSUMER_KEY
, YOUR_CONSUMER_SECRET
, YOUR_ACCESS_TOKEN
, and YOUR_ACCESS_TOKEN_SECRET
placeholders with your actual Twitter API credentials.
You can also use other social media platforms like Facebook, Instagram, LinkedIn, etc. by using their respective APIs and endpoints.
Here are some examples of how to fetch news feed from other social media platforms:
Facebook:
$endpoint = 'https://graph.facebook.com/v13.0/me/feed';
$params = array(
'access_token' => 'YOUR_ACCESS_TOKEN',
'fields' => 'message,created_time'
);
Instagram:
$endpoint = 'https://graph.instagram.com/v13.0/me/media';
$params = array(
'access_token' => 'YOUR_ACCESS_TOKEN',
'fields' => 'caption,created_time'
);
LinkedIn:
$endpoint = 'https://api.linkedin.com/v2/feed';
$params = array(
'access_token' => 'YOUR_ACCESS_TOKEN',
'fields' => 'title,created_at'
);
Note that each platform has its own API documentation and requirements, so be sure to check the documentation for the specific platform you're interested in using.