保存facebook评论到mysql数据库


save facebook comment to mysql database

如何将facebook评论保存到mysql数据库?我希望能够在另一个页面上搜索评论

你的意思是你评论的地方,例如,你的墙,评论到你的mysql数据库?

如果是,你需要学习Facebook API (Graph API)

<?php
// displays some comments for a certain url
$url = 'http://developers.facebook.com/docs/reference/fql/comment/';
// fql multiquery to fetch all the data we need to display in one go
$queries = array('q1' => 'select post_fbid, fromid, object_id, text, time from comment where object_id in (select comments_fbid from link_stat where url ="'.$url.'")',
                 'q2' => 'select post_fbid, fromid, object_id, text, time from comment where object_id in (select post_fbid from #q1)',
                 'q3' => 'select name, id, url, pic_square from profile where id in (select fromid from #q1) or id in (select fromid from #q2)',
                 );
// note format json-strings is necessary because 32-bit php sucks at decoding 64-bit ints :(
$result = json_decode(file_get_contents('http://api.facebook.com/restserver.php?format=json-strings&method=fql.multiquery&queries='.urlencode(json_encode($queries))));
$comments = $result[0]->fql_result_set;
$replies = $result[1]->fql_result_set;
$profiles = $result[2]->fql_result_set;
$profiles_by_id = array();
foreach ($profiles as $profile) {
  $profiles_by_id[$profile->id] = $profile;
}
$replies_by_target = array();
foreach ($replies as $reply) {
  $replies_by_target[$reply->object_id][] = $reply;
}
/**
 * print a comment and author, given a comment passed in an an array of all profiles.
 * @param object $comment as returned by q1 or q2 of the above fql queries
 * @param array $profiles_by_id, a list of profiles returned by q3, keyed by profile id
 * @returns string markup
 */
function pr_comment($comment, $profiles_by_id) {
  $profile = $profiles_by_id[$comment->fromid];
  $author_markup = '';
  if ($profile) {
    $author_markup =
      '<span class="profile">'.
        '<img src="'.$profile->pic_square.'" align=left />'.
        '<a href="'.$profile->url.'" target="_blank">'.$profile->name.'</a>'.
      '</span>';
  }
  return
    $author_markup.
    ' ('.date('r', $comment->time).')'.
    ': '.
    htmlspecialchars($comment->text);
}
print '<html><body>';
// print each comment
foreach ($comments as $comment) {
  print
    '<div style="overflow:hidden; margin: 5px;">'.
      pr_comment($comment, $profiles_by_id).
    '</div>';
  // print each reply
  if (!empty($replies_by_target[$comment->post_fbid])) {
    foreach ($replies_by_target[$comment->post_fbid] as $reply) {
      print
        '<div style="overflow:hidden; margin: 5px 5px 5px 50px">'.
          pr_comment($reply, $profiles_by_id).
        '</div>';
    }
  }
}

?>

有几种方法可以做到。

第一种方法是一次性获得所有注释。您必须定期这样做以获得新的注释,并避免在数据库中重复旧的注释。

这可以通过使用您的页面url访问Graph API来实现:

https://graph.facebook.com/comments/?ids=http://example.com/your_page

返回JSON格式的注释,您必须对其进行解析。如果有太多,将会有一个"分页"散列告诉你下一页的地址。


第二种方法是跟踪新的评论并立即保存它们。这避免了重取副本的问题。这将需要使用Javascript和Facebook js事件。

FB.Event.subscribe('comment.create', function(response) {
  var commentQuery = FB.Data.query('SELECT fromid, text FROM comment WHERE post_fbid=''' + response.commentID + ''' AND object_id IN (SELECT comments_fbid FROM link_stat WHERE url=''' + response.href + ''')');
  FB.Data.waitOn([commentQuery], function () {
    text = commentQuery.value[0].text;
    // Use your preferred way to inform the server to save comment
    $.post( 'http://example.com/comment', text )
  });
});

下面的示例在客户端获取注释。但是你也可以在服务器端这样做。

当然,您需要包含Facebook的Javascript库,并在服务器上实现发布操作(http://example.com/comment)。

FB.Event.subscribe('comment.create',
function(response) {
onCommentCreate(response.commentID,response.href); //Handle URL on function to store on database
alert(response.href); //it gives you url
}
);
function onCommentCreate(commentID,href) {
    $.ajax({
        type: 'POST',
        url: 'handlecomment.php',
        data: {commentid:commentID,href:href},
        success: function(result)
        {
        alert(result);
        }
    });
}
//hadlecomment.php 

<?php 
error_reporting(E_ERROR);
  $commentid=$_POST['commentid'];
  $url=$_POST['href'];
  $pid=substr($url,strpos($url, 'comments')+8);
 // Remember to copy files from the SDK's src/ directory to a
  // directory in your application on the server, such as php-sdk/
  require_once('php-sdk/facebook.php');
  $config = array(
    'appId' => 'YOUR_APP_ID',
    'secret' => 'YOUR_APP_SECRET',
  );
  $facebook = new Facebook($config);
  $user_id = $facebook->getUser();
 $accesstoken=$facebook->getAccessToken();
 if($user_id) {
  // We have a user ID, so probably a logged in user.
  // If not, we'll get an exception, which we handle below.
  try {
        $facebook->setAccessToken($accesstoken);
        $fql = 'SELECT text from comment where id = ' . $commentid;
        $ret_obj = $facebook->api(array(
                                   'method' => 'fql.query',
                                   'query' => $fql,));
$comment= $ret_obj[0]['text'] ;
     $insert_comment="insert into comments(pid,comment) values($pid,$comment)";
mysql_query($insert_comment);

  } catch(FacebookApiException $e) {
    // If the user is logged out, you can have a 
    // user ID even though the access token is invalid.
    // In this case, we'll get an exception, so we'll
    // just ask the user to login again here.
    $login_url = $facebook->getLoginUrl(); 
    echo 'Please <a href="' . $login_url . '">login.</a>';
    error_log($e->getType());
    error_log($e->getMessage());
  }   
} else {
  // No user, so print a link for the user to login
  $login_url = $facebook->getLoginUrl();
  echo 'Please <a href="' . $login_url . '">login.</a>';
}
  ?>
?>

//YOu need to set data-href of comment should be look like this...
//i am using more comments on my website so i looped through to add comment 

while($result=mysql_fetch_assoc(mysql_query($query)))
{
  $pic_id=$result['pic_id']; // i have saved unique pic id in my database for all images so  i am    
//retrieving that here
<div class="fb-comments" style=' position:relative;left:55px;top:10px;'  data-href="<?php echo 'http://www.lpuphotography.edulogics.in/votography.php/comments' . $pic_id; ?>" data-width="470" data-num-posts="2"></div>
}
//if you are using single comment
<div class="fb-comments" style=' position:relative;left:55px;top:10px;'  data-href="<?php echo 'http://www.lpuphotography.edulogics.in/votography.php/comments101'  ?>" data-width="470" data-num-posts="2"></div>
//101 is comment id , u can set what ever you want