I am trying to get user's fan page post using the following code, but it's give me warning
Warning: file_get_contents(https://graph.facebook.com/782176371798916/posts): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
$page_posts = file_get_contents('https://graph.facebook.com/'.$page_id.'/posts');
$pageposts = json_decode($page_posts);
foreach ($pageposts["data"] as $fppost) {
echo $fppost['message'];
}
SO, how is the correct way to get user's fan page post?
The solution I found is by using the following code:
$pageposts = $facebook->api('/'.$page_id.'/posts', 'GET');
foreach ($pageposts["data"] as $fppost) {
echo $fppost['message'];
}
You didn't send the access_token parameter, just add it and it should work like charm:
$page_id = 'smashmag'; // Page ID or username
$token = '553435274702353|OaJc7d2WCoDv83AaR4JchNA_Jgw'; // Valid access token, I used app token here but you might want to use a user token .. up to you
$page_posts = file_get_contents('https://graph.facebook.com/'.$page_id.'/posts?fields=message&access_token='.$token); // > fields=message < since you want to get only 'message' property (make your call faster in milliseconds) you can remove it
$pageposts = json_decode($page_posts);
foreach ($pageposts->data as $fppost) {
if (property_exists($fppost, 'message')) { // Some posts doesn't have message property (like photos set posts), errors-free ;)
print $fppost->message.'</br>';
}
}
Related
I was working in php
I did the work and sottoiscrizione
facebook api is v.2.2
but now there is a problem
how do I read the updates of the feeds I get ?
The code is :
<?php
//file of program
require_once('LoginFb.php');
require_once('FbClass.php');
require_once('dbClass.php');
require_once('FacebookClass.php');
//receive a Real Time Update
$method = $_SERVER['REQUEST_METHOD'];
// In PHP, dots and spaces in query parameter names are converted to
// underscores automatically. So we need to check "hub_mode" instead
// of "hub.mode".
if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' &&
$_GET['hub_verify_token'] == 'thisisaverifystring') {
echo $_GET['hub_challenge']; //print the code on the page that Facebook expects to read for confirmation
} else if ($method == 'POST') {
$updates = json_decode(file_get_contents("php://input"), true);
// Replace with your own code here to handle the update
// Note the request must complete within 15 seconds.
// Otherwise Facebook server will consider it a timeout and
// resend the push notification again.
$testo=json_decode($updates["entry"]);
$var=fopen("nome_file.txt","a+");
fwrite($var, "ciao");
fwrite($var, $updates );
fclose($var);
error_log('updates = ' . print_r($updates, true));
}
?>
In the above file "$update" contains an updated feed, but how to extract?
Note: subscription WORKS and updates arrived on my server.
Help me please :)
According to the Facebook documentation [link]:
Note that real-time updates only indicate that a particular field has changed, they do not include the value of those fields. They should be used only to indicate when a new Graph API request to that field needs to be made.
So, you don't get the updated data instead you get the updated feild name. On receiving an update, you should extract the changed field (I have explained this below) and make a new Graph API request to that field. Finally, you will get the updated field data.
How to extract the user name and changed field?
You receive this:
{"entry":[{"id":"****","uid":"****","time":1332940650,"changed_fields":{"status"]}],"object":"user"}
where "id" is my pageId and "changed_fields" is an array of changed fields.
You can extract these as following:
$entry = json_decode($updates["entry"]); <br>
$page = json_decode($entry["uid"]); <br>
$fields = json_decode($entry["changed_fields"]);
Hope it helps! :)
No function -> the respose contain a array of array the correct code is:
$json = json_decode($updates["entry"][0]["uid"], true);
I searched for this but most of the questions related to this are for API's with other services.
I'm building an API that allows game developers to send and retrieve user info from my database.
I was finally able to put together the API, but now I need to call the API.
1st when the game initiates, it sends us the game developers key their developer id and game id.
//Game loads, get developer key, send token and current high score
// == [ FIRST FILTER - FILTER GET REQUEST ] == //
$_GET = array_map('_INPUT', $_GET); // filter all input
// ====================================== //
// ============[ ACTION MENU ]=========== //
// ====================================== //
if(!empty($_GET['action']) && !empty($_GET['user']) && !empty($_GET['key']) && !empty($_GET['email']) && !empty($_GET['password'])): // if key data exists
switch($_GET['action']):
//athenticate game developer return and high score
case 'authenticate':
$db = new PDO('mysql:host=localhost;dbname=xxxx', 'xxxx', 'xxxx');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$st = $db->prepare("SELECT * FROM `game_developers_games` WHERE `id` = :gameid AND `developer_id`=:user AND `key`= :key AND `developer_active` = '1'"); // need to filter for next auction
$st->bindParam(':user', $_GET['user']); // filter
$st->bindParam(':key', $_GET['key']); // filter
$st->execute();
$r = $st->fetch(PDO::FETCH_ASSOC);
if($st->rowCount() == 0):
$return = array('DBA_id'=>'0000');
echo json_encode($return);
else:
$token = initToken($_GET['key'],$_GET['user']);
if($token == $r['API_Token']):
$return = array(
'DBA_id'=>$token,
'DBA_servertime'=>time(),
'DBA_highscore'=>$r['score'],
);
echo json_encode($return);
endif;
endif;
break;
Here's the script the game developer will have to add to their game to get the data when the game loads. Found this on another stackoverflow question but it's not working.
$.getJSON("https://www.gamerholic.com/gamerholic_api/db_api_v1.php? user=1&key=6054abe3517a4da6db255e7fa27f4ba001083311&gameid=1&action=authenticate", function () {
alert("aaa");
});
Try adding &callback=? to the end of the url you are constructing. This will enable jsonp that is accepted by cors.
$.getJSON("https://www.gamerholic.com/gamerholic_api/db_api_v1.php?user=1&key=6054abe3517a4da6db255e7fa27f4ba001083311&gameid=1&action=authenticate&callback=?", function () {
alert("aaa");
});
As per cross domain origin policy you cannot access cross domain url using jquery getJson function.
A callback is required to manage cross domain request using json and it needs to be handled on the server as well as the client end.
Also make sure to check the response using firebug or similar tool because as of now it is returning response code as 200.
I am mentioning two threads here which can guide you the right way
Jquery getJSON cross domain problems
http://www.fbloggs.com/2010/07/09/how-to-access-cross-domain-data-with-ajax-using-jsonp-jquery-and-php/
Ok, so following some instructions I found in another post here on StackOverflow, I have constructed a script to get a fan pages feed and turn it into an RSS2 feed. However, the script required a few changes and Im not the best programmer in the world, so I need a little help.
Im getting this error:
Warning: Invalid argument supplied for foreach() in feed.php on line 48
Im not sure what the invalid argument is all about.
<?
// error reporting
echo '<pre>';
ini_set('display_errors', 'on');
error_reporting(E_ALL);
// require your facebook php sdk
require('./facebook/facebook.php');
// include the feed generator feedwriter file
include("./feed/FeedWriter.php");
// config secret key and appid
$config = array(
'appId' => '',
'secret'=> ''
);
// Initialize
$facebook = new Facebook($config);
// Set Apps Permissions Request
$permission_scope = "";
// get users access token
$access_token = $facebook->getAccessToken();
// get page post
$feed_url = 'https://www.facebook.com/Ritualdubstep/feed?access_token='.$access_token;
$feed_json = file_get_contents($feed_url);
$feed_data = json_decode($feed_json);
// create the feedwriter object
$feed = new FeedWriter(RSS2);
$feed->setTitle('Ritual Dubstep'); // set your feed title
$feed->setLink('https://www.facebook.com/Ritualdubstep'); // set the url to the feed page you're generating
$feed->setChannelElement('updated', date(DATE_RSS , time()));
$feed->setChannelElement('author', array('name'=>'Ritual Dubstep SF')); // set the author name
// iterate through the facebook response to add items to the feed
foreach($feed_data['data'] as $entry){
if(isset($entry["message"])){
$item = $feed->createNewItem();
$item->setTitle($entry["from"]["name"]);
$item->setDate($entry["updated_time"]);
$item->setDescription($entry["message"]);
if(isset($entry["link"]))
$item->setLink(htmlentities($entry["link"]));
$feed->addItem($item);
}
}
// generate feed
$feed->genarateFeed();
?>
Generally it means that the first argument in the foreach call (in this case $feed_data['data']) is not a valid array.
Make sure that $feed_data['data'] exists (isset($feed_data['data'])) and that it is an array (is_array($feed_data['data'])) before running entering the foreach loop.
And - as shapeshifter mentioned in the comments - you might want to start troubleshooting by var_dump($feed_data['data']) right before you start the foreach loop to see what's being generated.
I am using the following code to retrieve an amount of Tweets from the Twitter API:
$cache_file = "cache/$username-twitter.cache";
$last = filemtime($cache_file);
$now = time();
$interval = $interval * 60; // ten minutes
// Check the cache file age
if ( !$last || (( $now - $last ) > $interval) ) {
// cache file doesn't exist, or is old, so refresh it
// Get the data from Twitter JSON API
//$json = #file_get_contents("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=" . $username . "&count=" . $count, "rb");
$twitterHandle = fopen("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$username&count=$count", "rb");
$json = stream_get_contents($twitterHandle);
fclose($twitterHandle);
if($json) {
// Decode JSON into array
$data = json_decode($json, true);
$data = serialize($data);
// Store the data in a cache
$cacheHandle = fopen($cache_file, 'w');
fwrite($cacheHandle, $data);
fclose($cacheHandle);
}
}
// read from the cache file with either new data or the old cache
$tweets = #unserialize(file_get_contents($cache_file));
return $tweets;
Of course $username and the other variables inside the fopen request are correct and it produces the correct URL because I get the error:
Warning: fopen(http://api.twitter.com/1/statuses/user_timeline.json?screen_name=Schodemeiss&count=5) [function.fopen]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/ellexus1/public_html/settings.php on line 187
that ^^ error returns whenever I try and open my page.
Any ideas why this might be? Do I need to use OAuth to even just get my tweets!? Do I have to register my website as somewhere that might get posts?
I'm really not sure why this is happening. My host is JustHost.com, but I'm not sure if that makes any diffrence. All ideas are welcome!
Thanks.
Andrew
PS. This code lies inside a function where username, interval and count are passed in correctly, hence in the error code its created a well formed address.
Chances are you are getting rate-limited
400 Bad Request: The request was invalid. An accompanying error
message will explain why. This is the status code will be returned
during rate limiting.
150 requests per hour for non authenticated calls (Based on IP-addressing)
350 requests per hour for authenticated calls (Based on the authenticated users calls)
You have to authenticate to avoid these errors popping up.
And also please use cURL when dealing with twitter. I've used file_get_contents and fopen to call the twitter API, and found that it is very unreliable. You would get hit with that every now and then.
Replace the fopen with
$ch = curl_init("http://api.twitter.com/1/statuses/user_timeline.json?screen_name=$username&count=$count");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$it = curl_exec($ch); //content stored in $it
curl_close($ch);
This may help
Error codes
https://developer.twitter.com/en/docs/basics/response-codes.html
Error codes defination is given in above link
im trying to update my news feed on facebook. Im using the new graph api. I can connect to graph, but when i try to publish some content to the feed object, nothing happens.
here´s my code:
<?php
$token = "xxxx";
$fields = "message=test&access_token=$token";
$c = curl_init("http://graph.facebook.com/me/feed");
curl_setopt($c,"CURLOPT_POST", true);
curl_setopt($c,"CURLOPT_POSTFIELDS",$fields);
$r = curl_exec($c);
print_r($r);
this returns:
{"error":{"type":"QueryParseException","message":"An active access token must be used to query information about the current user."}}1
then I try to pass access_token via GET:
$c = curl_init("http://graph.facebook.com/me/feed?access_token=$token");
this returns:
{"data":[]}1
Am I doing something wrong?
thanks
I found my error!
I was putting CURL options as a string rather than constants.
oopps...