我目前正试图通过使用Facebook api来获取和解析用户的事件。为此,我正在使用下面的功能。
function facebook_get_events($facebookSession) {
// make the API call and get array of event objects
$events = (new FacebookRequest($facebookSession, 'GET', '/me/events')->execute()->getGraphObject();
log("Got events from facebook " . count($events));
foreach ($events as $event) {
echo $event->getProperty('id');
}
return events;
}
问题:问题是它不能正常工作。在日志中我注意到数组中只有一个元素。顺便说一句,我假设事件是一个数组,因为根据Facebook的文档,响应是"一系列事件对象"。 Click here to check out the doc link
关于id的打印,没有显示任何内容。
为了检查请求是否正确,我还使用了Facebook的Graph API Explorer,它正确地返回事件列表。结果结构如下所示(由于隐私问题,信息已被删除)。
{
"data": [
{
"name": "...",
"start_time": "...",
"location": "...",
"rsvp_status": "...",
"id": "..."
},
{
"name": "...",
"start_time": "...",
"timezone": "...",
"rsvp_status": "...",
"id": "..."
}
],
.....
}
我还检查了我的权限是否正确,并且我可以确认我是否包含user_events权限。我认为我的问题与我如何解析响应有关。
根据评论的要求,我还对事件做了一个var_dump。以下是我收到的内容的快照。
object(Facebook\GraphObject)#5 (1) { ["backingData":protected]=> array(2) { ["data"]=> array(25) { [0]=> object(stdClass)#6 (5) { ["id"]=> string(15) “…” ["name"]=> string(11) “..”. [“location"]=> string(14) “…” ["start_time"]=> string(24) “…”
进度1:
我还尝试使用此代码,调用“数据”和“数据”。财产,但仍然没有管理。
function facebook_get_events($facebookSession) {
// make the API call and get array of event objects
$events = (new FacebookRequest($facebookSession, 'GET', '/me/events')->execute()->getGraphObject();
log("Got events from facebook " . count($events->getProperty('data')));
foreach ($events->getProperty('data') as $event) {
echo $event->getProperty('id');
}
return events;
}
上面的代码什么都没打印出来。
答案 0 :(得分:2)
这是最简单的方法:
$eventResponse = (new FacebookRequest($session, 'GET', '/me/events'))->execute()->getResponse();
$events = $eventResponse->data;
foreach ($events as $event) {
echo $event->name;
//echo $event->id;
//echo $event->name;
//echo $event->start_time;
//echo $event->timezone;
//echo $event->location;
}
这是很好的方式:
班级声明:
class GraphEventlist extends GraphObject implements Iterator
{
/**
* @var GraphEvent[]
*/
protected $backingData = array();
public function __construct($raw)
{
foreach ($raw['data'] as $eventArray) {
if ($eventArray instanceof \stdClass) {
$eventArray = get_object_vars($eventArray);
}
$this->backingData[$eventArray['id']] = $eventArray;
}
}
public function current()
{
return $this->getProperty(key($this->backingData), 'GraphEvent');
}
public function key()
{
return key($this->backingData);
}
public function next()
{
next($this->backingData);
}
public function rewind()
{
reset($this->backingData);
}
public function valid()
{
return null !== key($this->backingData);
}
}
class GraphEvent extends GraphObject
{
}
获取活动
$events = (new FacebookRequest($session, 'GET', '/me/events'))->execute()->getGraphObject('GraphEventlist');
迭代:
foreach ($events as $event) {
echo $event->getProperty('name');
}
按ID获取单个活动:
var_dump($events->getProperty('6499**********4', 'GraphEvent'));