简体   繁体   中英

PHP Facebook Graph API get posts comments WITH user photo field

When I get the comments of a post

https://graph.facebook.com/v2.4/ POST_ID /comments

I get the comment, the person's name (and id), but not their profile picture.

To recover his profile picture, I must repeat each time a GET query

https://graph.facebook.com/ USER_ID /picture?redirect=false

So if there are 150 comments, I make 150 GET queries just to retrieve the URL of the profile photo...

Page loading time sometimes takes up to 30 seconds...

Is it possible to recover url fields of the profile photo directly in the JSON with all comments?

Why would you need to retrieve the profile picture URLs in the first place? You have the user ids already, so you can simply use https://graph.facebook.com/v2.4/{user_id}/picture as the src attribute value of an img element directly – it will redirect to the correct location of the actual image on Facebook's CDN.

Or do you need the actual image URLs for another purpose, outside of the realm of a web page …?

In that case, you can use the Field Expansion feature of the API (so you don't need a batch request):

/post_id/comments?fields=message,from{name,picture}

That will get you the content of the comment, plus the name and profile picture URL of the user that made the comment. (If you need any more fields, you have to add them to the list.)

This can be done with batch request, but it is a little difficult:

curl -k \
-F 'access_token={YOUR_USER_ACCESS_TOKEN}' \
-F 'include_headers=false' \
-F 'batch=[
  {
    "method":"GET",
    "name":"postcomments",
    "relative_url":"{post_id}?fields=comments.fields(from.fields(id)).limit(50)",
  }, 
  {
    "method":"GET",
    "name":"pics1",
    "relative_url":"?ids={result=postcomments:$.comments.data.[0:50:1].from.id}&fields=id,name,picture"
  }]' \
https://graph.facebook.com

Exchange {post_id} with a valid post id, and {YOUR_USER_ACCESS_TOKEN} with an actual User Access Token.

Be aware that the /?ids= endpoint can only be used for 50 ids at once, meaning you need to align the number of

  {
    "method":"GET",
    "name":"pics1",
    "relative_url":"?ids={result=postcomments:$.comments.data.[0:50:1].from.id}&fields=id,name,picture"
  }

with the number you set as limit in the first query (limit/50). Furthermore, you'll have to adjust the [0:50:1] part so that it reflects the actual "positions".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM