How To Display Facebook Page Events on Website using PHP?

Let's code!

Do you have an event manager on your website? Do you create events on your Facebook page? If your answer is both YES, you're wasting a lot of time managing your brand's events information online.

What if there's a way to create an event ONCE, and then let it appear both on your Website and Facebook page? Will you be happy saving your precious time? Our code for today will make you happy then, just like we are!

Today we're gonna talk about how to display publicly available Facebook Page EVENTS on your website. This one is great if you want your Facebook page events to be shown in your website in a synchronized way.

Once you created or updated an event on Facebook, it will be automatically reflected on your website too. The advantages and risks of this is almost the same with what I discussed in my first post  related to this one.

Today post will include the following contents:

1.0 Source code overview
2.0 Final code output

3.0 Create index.php file with a page title
4.0 Make index.php bootstrap ready
5.0 Add a page header
6.0 Get your Facebook page ID
7.0 Specify the "since" and "until" dates
8.0 Get your page access token
9.0 Prepare the FB graph API link
10.0 Decode the JSON string
11.0 Prepare the table and loop
12.0 Put the event values in variables
13.0 Put the values in TD tags

14.0 How to display past events?
15.0 How to display upcoming events?
16.0 How to change the order of events?

17.0 What people say about this code?
17.1 From blog comments
17.2 From emails
17.3 From Facebook messages

18.0 Download the complete source code
19.0 SociableKIT Facebook Page Events Website Plugin

21.0 What's next?
22.0 Related source codes
23.0 Some notes

1.0 Source Code Overview

Here's an overview of what our code does:

1.1 Gets events listed with data such as event image, name, time, description, ect. from your Facebook fan page without using any Facebook PHP SDK, just the Facebook Graph API!

1.2 Display these event data to a webpage (assuming it is your WordPress or PHP website.)

1.3 Show some awesome UI powered by Bootstrap. If you’re not yet familiar with this awesome front-end framework, see our step by step Bootstrap tutorial here.

2.0 Display Facebook Page Events On Website - Output

We have to know where we are going. If we completed the tutorial below, we will achieve the following LEVEL 1 source code output.

2.1 BASIC Source Code - Output Preview

2.2 PRO Source Code - Output Preview

The PRO source code outputs proves that you can add and customize more features. It's easier and faster if you will learn by following our tutorial below.

Downloading our source codes is your huge advantage as well. For now, let’s proceed to the step by step tutorial of our BASIC source code. Enjoy!

3.0 Create An index.php File And Put A Page Title

Create a new index.php file and place the following code.

<?php $page_title ="Display Facebook Page Events on Website"; ?>

4.0 Make index.php Bootstrap Ready

Add the following code on our index.php to make it Bootstrap ready. Bootstrap allows us to have a decent looking user interface, if you're not familiar with it, please visit our Bootstrap step by step guide.

In the code below, you will see that we put <?php echo $page_title; ?> inside the title tag. That's how we used the $page_title variable from the previous section.

<!DOCTYPE html>
<html lang="en">
<head>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">

	<title><?php echo $page_title; ?></title>

	<!-- Bootstrap CSS -->
	<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" media="screen">

</head>
<body>
	

<div class="container">

<!-- events will be here -->

</div>

<!-- jQuery library -->
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

<!-- bootstrap JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

</body>
</html>

5.0 Add A Page Header

Replace <!-- events will be here --> comment above with the following code.

<div class="page-header">

<h1><?php echo $page_title; ?></h1>

</div>

6.0 Get Your Facebook Page ID

The testing Facebook page I used was https://www.facebook.com/postedbydsm, and its Facebook page id is postedbydsm.

How did I get that ID? Just use this tool I made for you.

You must use your Facebook page ID. Once you get your Facebook page ID, place the following code after the previous section's code.

<?php $fb_page_id = "postedbydsm"; ?>

7.0 Specify The “Since” and “Until” Dates To Get The Events

Specifying the 'since' and 'until' dates below will get all the Facebook page events 2 years before and 2 years after the current year in your page.

$year_range = 2;

// automatically adjust date range
// human readable years
$since_date = date('Y-01-01', strtotime('-' . $year_range . ' years'));
$until_date = date('Y-01-01', strtotime('+' . $year_range . ' years'));

// unix timestamp years
$since_unix_timestamp = strtotime($since_date);
$until_unix_timestamp = strtotime($until_date);

// or you can set a fix date range:
// $since_unix_timestamp = strtotime("2012-01-08");
// $until_unix_timestamp = strtotime("2018-06-28");

// page access token
$access_token = "YOUR_ACCESS_TOKEN";

8.0 Get your page access token

Before you can get events data from your Facebook page via the graph API, you need a "page" access token.

Follow this detailed tutorial about how to get a page access token: How to get a Facebook page access token?

Replace YOUR_ACCESS_TOKEN of the previous section with your page access token.

9.0 Prepare The FB Graph API Link

This link is where the JSON string will be retrieved.

We get the JSON contents via PHP's file_get_contents() function.

$fields="id,name,description,place,timezone,start_time,cover";

$json_link = "https://graph.facebook.com/v3.0/{$fb_page_id}/events/attending/?fields={$fields}&access_token={$access_token}&since={$since_unix_timestamp}&until={$until_unix_timestamp}";

$json = file_get_contents($json_link);

10.0 Decode The JSON String

We have to decode the JSON string using the json_decode() function and convert it to an associative array by setting the second parameter to true.

We also used JSON_BIGINT_AS_STRING parameter since Facebook uses large integers (eid) and we don't want PHP to simplify the value.

$obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);

// for those using PHP version older than 5.4, use this instead:
// $obj = json_decode(preg_replace('/("\w+"):(\d+)/', '\\1:"\\2"', $json), true);

11.0 Prepare The Table And Loop

This time we are actually retrieving the events from Facebook. We are going to put it in an HTML table powered by Bootstrap, that's why we have to classes below.

echo "<table class='table table-hover table-responsive table-bordered'>";

    // count the number of events
    $event_count = count($obj['data']);

    for($x=0; $x<$event_count; $x++){
        // facebook page events will be here
    }
echo "</table>";

12.0 Put The Event Values In Variables

Inside our for loop, we are going to put the event values in variables.

// set timezone
date_default_timezone_set($obj['data'][$x]['timezone']);

$start_date = date( 'l, F d, Y', strtotime($obj['data'][$x]['start_time']));
$start_time = date('g:i a', strtotime($obj['data'][$x]['start_time']));
 
$pic_big = isset($obj['data'][$x]['cover']['source']) ? $obj['data'][$x]['cover']['source'] : "https://graph.facebook.com/v2.7/{$fb_page_id}/picture?type=large";

$eid = $obj['data'][$x]['id'];
$name = $obj['data'][$x]['name'];
$description = isset($obj['data'][$x]['description']) ? $obj['data'][$x]['description'] : "";

// place
$place_name = isset($obj['data'][$x]['place']['name']) ? $obj['data'][$x]['place']['name'] : "";
$city = isset($obj['data'][$x]['place']['location']['city']) ? $obj['data'][$x]['place']['location']['city'] : "";
$country = isset($obj['data'][$x]['place']['location']['country']) ? $obj['data'][$x]['place']['location']['country'] : "";
$zip = isset($obj['data'][$x]['place']['location']['zip']) ? $obj['data'][$x]['place']['location']['zip'] : "";

$location="";

if($place_name && $city && $country && $zip){
	$location="{$place_name}, {$city}, {$country}, {$zip}";
}else{
	$location="Location not set or event data is too old.";
}

13.0 Put The Values In TD Tags

This is how we put values in the HTML table for our output. Put this code inside the for loop, after the code in section 12.0.

echo "<tr>";
	echo "<td rowspan='6' style='width:20em;'>";
		echo "<img src='{$pic_big}' width='200px' />";
	echo "</td>";
echo "</tr>";
 
echo "<tr>";
	echo "<td style='width:15em;'>What:</td>";
	echo "<td><b>{$name}</b></td>";
echo "</tr>";
 
echo "<tr>";
	echo "<td>When:</td>";
	echo "<td>{$start_date} at {$start_time}</td>";
echo "</tr>";
 
echo "<tr>";
	echo "<td>Where:</td>";
	echo "<td>{$location}</td>";
echo "</tr>";
 
echo "<tr>";
	echo "<td>Description:</td>";
	echo "<td>{$description}</td>";
echo "</tr>";
 
echo "<tr>";
	echo "<td>Facebook Link:</td>";
	echo "<td>";
		echo "<a href='https://www.facebook.com/events/{$eid}/' target='_blank'>View on Facebook</a>";
	echo "</td>";
echo "</tr>";

14.0 How To Display Past Events?

To display all past event, you just have to set the 'since date' to the past x years (set in $year_range variable), and the 'until date' to yesterday.

// get events for the past x years
$year_range = 1;

// automatically adjust date range
// human readable years
$since_date = date('Y-01-01', strtotime('-' . $year_range . ' years'));
$until_date = date('Y-m-d', strtotime('-1 day'));

// unix timestamp years
$since_unix_timestamp = strtotime($since_date);
$until_unix_timestamp = strtotime($until_date);

15.0 How To Display Upcoming Events?

To display the events today and in the future, you just have to set the 'since date' to today and the 'until date' to the future date (affected by the $year_range variable)

// get events for the next x years
$year_range = 1;

// automatically adjust date range
// human readable years
$since_date = date('Y-m-d');
$until_date = date('Y-12-31', strtotime('+' . $year_range . ' years'));

// unix timestamp years
$since_unix_timestamp = strtotime($since_date);
$until_unix_timestamp = strtotime($until_date);

16.0 How to Change The Order Of The Events?

Unfortunately, Facebook API does not give us the ability to sort the order of events, but I made a workaround for it. Use the following before the 'for loop' code:

function sortFunction($a,$b){
	if ($a['start_time'] == $b['start_time']) return 0;
	return strtotime($a['start_time']) - strtotime($b['start_time']);
}
usort($obj['data'],"sortFunction");

The only disadvantage is that, it will only sort the currently loaded JSON content.

17.0 What People Say About This Code?

I'm so glad that other people are delighted by this code, here are some of them!

17.1 From Blog Comments

★★★★★ "Hi Mike, amazing tutorial." ~ simonerama

★★★★★ "Hello and THANK you for this amazing work! :)" ~ Sergio

★★★★★ "Did the trick for me. Thanks for the nice script!" ~ n0Fear

★★★★★ "Hi Mike, thanks for the great script. I'm a programming novice, but got this running the way I wanted to pretty quickly. I owe you a beer." ~ Bas Koole

★★★★★ "Hi it's working great :)" ~ Sebastian

17.2 From Emails

★★★★★ "I've got it working! You're a great man, will do some ad for you!" ~ Markus

★★★★★ "Hi Mike! BOOM, works great! Thanks again!" ~ Nick

★★★★★ "Perfect! Thank you very much! If I have some new jobs, I will contact you! Greetings from Germany." ~ Eric

★★★★★ "Thank you for the fast reply, yes this should work for me. I will contact you again. Thank you so much." ~ Ruocco

17.3 From Facebook Messages

★★★★★ "Hey Mate, code's a lifesaver (and time saver!)" ~ Andrew

★★★★★ "Thanks, I've been trying to get Facebook events on the website for 6+ months had no luck, decided last night to update the site which I haven't done in a while and thought I'd give it another go and found you're page through a google search." ~ Ward

★★★★★ "Mike it's great and simple! I like! Thank you!" ~ Jasmin

★★★★★ "You're a life saver, thanks so much." ~ Brendon

18.0 Download the Complete Source Code

You can get the source code by following the whole, well detailed tutorial above. But isn't it more convenient if you can just download the complete source code we used, and play around it?

There's a small fee in getting the complete source code, it is small compared to the value or skill upgrade it can bring you, or income you can get from your website project or business.

For a limited time only, I will give you the source code for a low price. Download the source code by clicking the green buy button below.

18.1 Download the BASIC Source Code

FEATURES BASIC
Manage events for your Facebook Page and website once Yes
Save time figuring out and coding these features on your website Yes
Display list of all events Yes
Display list of upcoming events Yes
Display list of past events Yes
Display event cover photo (profile picture if none) Yes
Display event title Yes
Display event date and time Yes
Display event location Yes
Display event description Yes
Link to actual Facebook page event (opens in new tab) Yes
Bootstrap UI enabled Yes
Responsive layout (great for mobile devices) Yes
Free email support for 6 months. Yes
Free source code updates. Yes
Download Now

18.2 Download the PRO Source Code

FEATURES PRO
All features of the BASIC source code Yes
Display number of people attending the event Yes
Display event in Google map with pointer Yes
Calendar view Yes
Responsive calendar view (great for mobile devices) Yes
Next Month button navigation Yes
Prev Month button navigation Yes
Highlight calendar cells with events Yes
Calendar cells with events will pop up event info when clicked Yes
Font awesome icons Yes
Link to Google Maps to view full map Yes
Tickets Link Yes
Object oriented programming. Yes
New compact and responsive design. Yes
Show event details on a modal / pop up. Yes
Show event details without refresh. Yes
Specify date range (in code) by number of months. Yes
Download Now

Do you need more reasons to download it?

MORE REASONS TO GET IT
Buy only once, use up to 10 websites and Facebook pages! Yes
No different kind of licenses. Yes
No monthly or any recurring fees. Yes
No need to rely on another website to render Facebook page events. Yes
No need for codes from other websites. Yes
You can learn more how to code, I love teaching and can give you free tips! Yes
Familiarize yourself with the Facebook Graph API. Yes
Tutorial above is always free. Yes
Completely customizable. Yes

Thank you for supporting our projects!

19.0 SociableKIT Facebook Page Events Website Plugin

You demanded it, we built it. A lot of people requested a website plugin version of this Facebook page events code. Now it is available. It works no matter what website platform you use. We have tried it in WordPress, Squarespace, Wix and more.

Please provide your Facebook page URL on the message, thanks!

21.0 What's Next?

Today we have learned how to show your Facebook page events on your website.

Did you know that you can also display Facebook photo albums and photos on your website?

Let us go to the next tutorial: How To Display Facebook PHOTOS on Website?

22.0 Related Source Codes

Did you know that you can also display other social media data on your website? I’ve created tutorials on them too, see the following:

Social Media Script Tutorials
Display Facebook Page EVENTS on Website
Display Facebook Page PHOTOS on Website
Display Facebook Page VIDEOS on Website
Display Facebook Page POSTS on Website
Display Instagram FEED On Your Website
Display Twitter FEED on Website
Display Google+ FEED on Website

23.0 Some Notes

#1 Found An Issue?

If you found a problem with this code, we can solve it faster via Email or FB message, please send me a message via email [email protected], or via our official Facebook page!

Please be more detailed about your issue. Best if you can provide an error message and your test or page URL. Thanks!

Please feel free to comment if you have any questions, suggestions, found something wrong or want to contribute to this code.

#2 Become a true Ninja!

  • 1. Subscribe to social media scripts tutorial news and updates.
  • 2. Be updated about what works and what does not work on social media APIs.
  • 3. Be notified for any related social media API updates.
100% Privacy. We will never spam you!

#3 Thank You!

Thanks for visiting our tutorial on how to display Facebook page events on website using PHP and Facebook Graph API!

Before you write a comment, please read this guide and our code of conduct.
400 replies
  1. Small Business Helper Limited
    Small Business Helper Limited says:

    Will this work for a Facebook BUSINESS Page?

    I’ve struggled with getting a Charity’s Facebook Business Events Calendar to synchronise with Google Calendar on their website.

    It seems Google Calendar likes ‘personal’ Facebook URL’s (found via Facebook>Events>Export) but doesn’t like Facebook’s ‘Business Page’ URL’s Note the slightly longer UID in the following Facebook Business Page for above said example…
    webcal://www.facebook.com/ical/u.php?uid=785985561&key=AQDd5WNUGMUz3HeN

  2. Mike Dalisay
    Mike Dalisay says:

    Hmmm are you talking about facebook business accounts? Sorry I haven’t tried it yet since I don’t have one.

    Please note that this script works with facebook pages only, not personal fb account.

    Thanks for your comment. :)

  3. heyitshenryy
    heyitshenryy says:

    not to sound like a total noob, although i am, is there a way to do this automatically when a new event is created? I’m creating a fan page for a client, and don’t want them to have to constantly update the page. i’ve tried googling it and got nothing.

  4. lsm007
    lsm007 says:

    Can I call the “city” that the event is hosted in? I checked the API documentation and it said to use $values[‘venue’][‘city’], I think…but that’s not working. Thoughts?

  5. Rich
    Rich says:

    Hi, relative noob im afraid. I’ve got the above working when I go to domain/events.php, works great. However, I know want to call the script from my menu_7.html file. Any ideas?

  6. Mike Dalisay
    Mike Dalisay says:

    @rich: currently, i see the event menu link is in http://www.g6club.co.uk/index.php?p=1_7_Events, not in http://www.g6club.co.uk/events.php

    i guess you want to include http://www.g6club.co.uk/events.php on your index.php, if you’re familiar, you can try something like include ‘events.php’; at the content part of you index

    @Andrew: Sorry man I only tried this with PHP. But I believe that there’s also a facebook sdk for asp.net and just use the same approach I used here.

  7. Rich
    Rich says:

    Hi Mike. Yeah, theres a link in 1_7 events to take you to events.php. What I want is to get rid of that link… have the results from the php show up directly in 1_7.. I’ll check out include, thanks.

  8. Mike Dalisay
    Mike Dalisay says:

    @souzapaul: I think its a yes. as long as it is a public event. you have to do multiple queries. For your Q2, “WHERE eid IN ( SELECT eid FROM event_member WHERE uid = 221167777906963 )”, this part of the script actually allows you to add multiple eids.

    @Romymk: maybe using the LIMIT clause on your sql query?

  9. Anonymous
    Anonymous says:

    Hey, thanks Code Ninja! It took me much longer than it should have to get this working but it was because despite having a degree in CompSci, I don’t do this type of stuff nor did I know if I was talking to FB correctly. The Examples and tests phps didn’t work for me but the index.php worked great. So after spending time on all of that stuff I figured out some very basic directions:

    1. create the app (like you said), I put in facebook.com/mypage/events in for web page

    2. save the code zip file and extract it, edit the index.php file: you will need the code and secret from the app you created in step 1, AND you will need the UID for the web page. If you don’t know it you can get it from one of the other iframe apps like the like’ button for your website.

    3. in index.php , put in your code and secret where it says, and also change your uid lower in the doc. save.

    4. upload index.php and the folder fb-sdk folder. to some place on your server.

    5. test the page.
    -Mike Quick

  10. Mike Quick
    Mike Quick says:

    @souzapaul, I just tried changing the following in index.php to show the top most recent events, thats all I need:

    $fql = “SELECT name, pic, start_time, end_time, location, description

    FROM event WHERE eid IN ( SELECT eid FROM event_member WHERE uid = 124398140915524 )
    ORDER BY start_time DESC LIMIT 0,10″;
    // ORDER BY start_time asc”;

    -Mike Quick

  11. Anonymous
    Anonymous says:

    Hi Mr Dalisay,

    i am not really into the material, so i dont get it: what are the steps that i need to do to display the events of my fansite to my existing webpage?
    Could you help me?

    Thanks a lot

    Shakermaker

  12. Anonymous
    Anonymous says:

    Ok I got this to show the events of a Group and personal facebook profile but I cannot get this to produce events of a Page created for the business, how do i configure the php to show a FB page events?

  13. Alain
    Alain says:

    Thank you so much for this. Been digging through the SDK and tutorial all day and I just couldn’t find my way through them.

    I see that there are lots of “thank you” comments. You can be proud !

    Alain, Paris, France.

  14. Unknown
    Unknown says:

    Does anyone know the code that unknown wrote earlier?
    “I have the code working but I would like to group events together like facebook such as…
    Today
    This week
    Upcoming
    Ongoing
    How would I change the code to achieve this???”

    Thank you all for your help!

  15. MMM
    MMM says:

    thanks, works fine so far… two things:

    1) how do i translate the date into another language (german, french…)?

    2) how to get street and city for the location? when i put in “venue” instead of “location” it outputs “Array”…

    thanks in advance for any help!

  16. StreathamMike
    StreathamMike says:

    Thanks for this Mike – It’s very useful.

    @Aditya Nayak asked is there a way to link to each individual event?

    As Mike said in his reply to @heyitshenryy: “You just have to wrap each event record with an href to a link”

    Obviously you will first need to find the eid value of the event to create the link. You get this by simply adding “eid” (without the quotes) to the SELECT statement.

    I used the following to select the next three events – change the LIMIT number to get the number of events you need (NOTE: using end_time > now() ensures that today’s events are included in the list but not past events)

    $fql = “SELECT eid, name, pic, start_time, end_time, location, description
    FROM event WHERE eid IN ( SELECT eid FROM event_member WHERE uid = 123456789012345 ) AND end_time > now()
    ORDER BY start_time asc LIMIT 0,3″;

    I made each event clickable by adding a href link to the //printing the data section around the whole <div class=”event”> element:

    i.e. I changed

    //printing the data
    echo “<div class=’event’>”;

    to

    //printing the data
    echo “<a href=’https://www.facebook.com/events/{$values[‘eid’]}’ title=’Click for more details on the Facebook Event page’><div class=’event’>”;

    and I closed the link by changing the last line of this section from

    echo “</div>”;

    to

    echo “</div></a>”;

    I hope this helps.

  17. Wella
    Wella says:

    Hey

    This code ist really awesome and i just built it into my page and formatted it like i wanted to. But I only get it worked wth your “page id”.

    The Fanpage that I wanted to display is -> http://www.facebook.com/clubsams

    I simply have to copy the Fanpage-ID or not? Or it’s the APP-id? User-id? And put it on the SQL Query?

    like: … IN ( SELECT eid FROM event_member WHERE uid = 318385904895 ) …

  18. Anonymous
    Anonymous says:

    Hi.
    Like Wella, I think this feature is awesome. BUT. I dont have any Appid, as I have made my fan page without developer.
    So what I really have is a url and thats it.

    Is it possible for me to show the events on my website?

  19. Anonymous
    Anonymous says:

    This is great. Thank you… but…

    Instead of events, I’m getting the below errors. Any ideas?

    “Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at /index.php:9) in /fb/src/facebook.php on line 37

    Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /index.php:9) in /fb/src/facebook.php on line 37″

  20. StreathamMike
    StreathamMike says:

    @s0uky,

    To display future and current events only – but not past events – an addition to the $fql SELECT statement is required, as mentioned in my earlier post above.

    If you add “AND end_time > now()” to the end of the SELECT statement this will ensure that past events are not displayed:

    Example:

    $fql = “SELECT eid, name, pic, start_time, end_time, location, description
    FROM event WHERE eid IN ( SELECT eid FROM event_member WHERE uid = 123456789012345 ) AND end_time > now()
    ORDER BY start_time asc LIMIT 0,3″;

    Please Note: as Facebook is based on California time – which was set in this php code at the start – you need to adjust the end_time part of the statement above if you are not in California.

    Example:

    California is GMT-8 hours so as I’m in London I need to add 8 hours to the Facebook end_time to get it to match my local time – so the end time statement becomes:

    AND end_time > now()+(8*60*60)

    Note: Time is calculated in seconds so we have the time difference from California of 8hours x 60minutes x 60 seconds.

    Of course you need to calculate the time difference in your local area for this to be correct for you. Just replace the 8 in the statement with the time difference in hours from California – 9 for CET for example.

    By using the event end_time rather than the event start_time your webpage will display events which are still current. If an event is on from 10am – 4pm it will be displayed on your web page until 4pm – after which time it becomes a past event and will no longer be shown.

    Regards
    Mike

    • s0uky
      s0uky says:

      Thank you! I’ll try it.

      I done it with PHP function strtotime().
      It works too, but it’s little bit complicated:

      $start_time = date( ‘g:i a’, $values[‘start_time’] );
      $end_time = date( ‘g:i a’, $values[‘end_time’] );

      $datum_akce = date(‘j-n-Y’, $values[‘start_time’]);
      $aktualni_datum = date(“j-n-Y”);

      if (strtotime($datum_akce) >= strtotime($aktualni_datum)) {
      //printing the data

  21. Joe
    Joe says:

    Alright, galleries and events, pretty easy, how about status’? I fake code pretty well and I’m good at reading it, but my strong suit is design and frontend tech, so bear with me…

    I’ve got my select statement:

    SELECT message FROM stream WHERE source_id=PAGE_ID AND actor_id=PAGE_ID

    I’ll probably build on this once I get this working, but I assume I can add various element from a status, such as image, timestamp, etc. I need to create variables for each of these then output them to the HTML with a little CSS. Anythign I’m missing?

    I’ve been doing some research that says you can’t pull imagery or links from status, but I would think if you have permission and pull the gallery, then you should be able to grab that img ID somehow.. any ideas or tips?

    I’m a newbie to FQL, so any help is appreciated.

    • Joe
      Joe says:

      I was able to get this simple statement working, I even added a couple parameters to grab the timestamp, name, and a couple other things. What I couldn’t figure out was how to pull over pics. the more I searched through Fb Developer network, the more I kept running into the same script: fbWall.

      Given some time and maybe some help from a better developer than me, I probably could have eventually got it, but this script does exactly what I want it to. I may try and deconstruct the script to see what I still needed to do in order to get it to work.

    • Joe
      Joe says:

      Like box and actually fan box have too many limitations first and foremost width and style requirements. fbWall eliminated all that it allows you full control over the feed enabling you to easily customize every part to better fit your site and design needs.

  22. barney
    barney says:

    Thanks for this Mike – It’s very useful, good job.
    My question is if you can give me some instructions regarding how to place an fb event attending button on my webpage? I searched for it many places, but nothing useful yet. Thank you in advance.

  23. loMB
    loMB says:

    Hi, unfortunately it’s not working for me.
    I don’t understand where I can find the APP_ID_Secret for “Events” – this is a Facebook App – how can I get a secret ID to that public APP?
    The appID for Events is ‘2344061033’ is there more?
    On my developer Page I see the appID and the secret ID all of my fanpage working apps …but those one are useless here I guess :-(
    I think I missed some important things here ;-) Anybody who can help me?

  24. loMB
    loMB says:

    Hi Mike
    I have found what I have make wrong – I haven’t us the same directory structure to the facebook library….shame on me :-)
    No it’s works very good. Great that u share that knwoledge! Thanks a lot
    loMB

  25. Anonymous
    Anonymous says:

    I want to use this on a site but I am having a hard time understanding APP Ids. I don’t own the Facebook account or web site I am using. Would I need to log in to Facebook under my clients name, create a ID with that? Then this ID is associated with that user? Or do I create an account for development purposes with Facebook and then I can develop for other sites with one ID. Just don’t understand how myself, the website and Facebook all interact.

  26. Anonymous
    Anonymous says:

    This is a great code sample. Many thanks for posting. I have been trying to create an equivalent snippet using JavaScript. Unfortunately the ‘select’ statement seems to blow up.

    As a test I ran
    “SELECT name, venue, location, start_time FROM event WHERE eid = xxx”. This works.

    However ‘SELECT name, pic, start_time, end_time, location, description FROM event WHERE eid IN ( SELECT eid FROM event_member WHERE uid = yyy ) ORDER BY start_time asc” does not seem to work

    Here is the code snippet. Any ideas

    FB.api(‘/event’,function(response)
    {

    var fql_query = ‘SELECT name, pic, start_time, end_time, location, description FROM event WHERE eid IN ( SELECT eid FROM event_member WHERE uid = xxx ) ORDER BY start_time asc’;

    alert(fql_query);

    var query = FB.Data.query(fql_query);

    query.wait(function(rows) {
    //
    alert(‘query results’);
    });

    });

  27. Mr. T
    Mr. T says:

    Thank for a job well done.
    Pls i want to be able to get information from Facebook with the keywords on Nigeria, Events, Wedding, Make Up Artists, Mobile Network, Photographers etc. This is not just on a particular fan/friend. Kindly assist

  28. Aurora
    Aurora says:

    I’m sorry. I really want to use this for my website, but I have no idea how to even get started using these type of things. is their a video or can you walk me thru the steps of putting this where it needs to go> I absolutley am clueless when it comes to this stuff.

  29. ali croft
    ali croft says:

    Excited to say I’ve been able to take your code and actually implement it, so, before I ask a question–THANK YOU!

    Here’s the page that will have the Facebook Events feed: http://alicroft.com/empresscal/
    It should be pulling data from: http://www.facebook.com/TheEmpressRva?sk=events

    Not sure why, but I’m getting a display of old events. Note that the first four events on my site’s feed are outdated, and if you visit the Facebook page it is supposed to be pulling from, you’ll see there is a new event (Best of Richmond Thank You at The Empress) that it isn’t listed on my custom feed. Any help would be greatly appreciated!

    • StreathamMike
      StreathamMike says:

      Ali,

      In order to display only current and future events you need to add “AND end_time > now()” to the end of the SELECT statement:

      For details please see my post in reply to @s0uky on Jan 29 above.

      StreathamMike

  30. Arthur Permis Levyssohn
    Arthur Permis Levyssohn says:

    Dear Mike,

    Thanks for your tutorial:

    It works great, but just have a question concerning startdate/starttime and enddate/endtime.

    I add an event which start at 07 april at 21:30 and ends at 08 april 01:00. But at the site it shows only:” on Sunday, April 08, 2012 – 5:30 am to 10:00 am “

    see: http://jackkunkels.nl/Display-Facebook-Events-To-Your-Website-with-PHP-and-FQL/

    facebook: http://www.facebook.com/pages/jackkunkels/162678887146825?sk=events

    How can I change this in index.php

    Thanks in advance
    Arthur

  31. Anonymous
    Anonymous says:

    How to make it FQL from events change to share links?

    I changed your coding on the FQL, but the image not work
    Result after changed your coding there
    http://www.miracle-mart.com/FB2

    Since I can post the coding on your blog…
    So I upload the index.php to my blog for your reference what is wrong on it.

    http://explorerhome.dyndns.org/photoevent/index.zip

    Thank you of your time and help and share this coding.

    Best Regards,
    Jimmy Chan
    http://explorerhome.dyndns.org/blog

  32. Jonathan
    Jonathan says:

    This is great and works well, but I’d like to list the profile image of those attending each event.
    Any idea of how I could add that to the code so when each event lists, it shows perhaps a random 5 people who have marked the event as ‘attending’?

  33. Jae
    Jae says:

    Hi, I have managed to create an app on facebook and fill in all the boxes in the widget.

    But nothing is showing up on my webpage. – Should i wait for you to get the codes up on your index.php file?

    Thanks

  34. Arthur Permis Levyssohn
    Arthur Permis Levyssohn says:

    Heee Mike, The +9 hours doesn’t work anymore, how come…>

    Still has the code:

    $fql = “SELECT eid, name, pic, start_time, end_time, location, description FROM event WHERE eid IN ( SELECT eid FROM event_member WHERE uid = 162678887146825 ) AND end_time > now()+(9*60*60) ORDER BY start_time asc LIMIT 0,3”;

    and date_default_timezone_set(‘America/Los_Angeles’);

    He doesn’t raise the time with 9 hours…!!!

    greetz
    Arthur

  35. Jae
    Jae says:

    Hi, Just asking once more, why the events has not showed up on my page?

    I created an app on facebook, and entered all the information into the widget.

    Is there anything more to do from here?

  36. ira
    ira says:

    On July 5th, Facebook changed something with the timezones and now I am getting December 31, 1969 for all event dates. Is anyone experiencing this?

    I even get the wrong dates using the sample files downloaded above, put directly on my server, unedited (aside from app id, etc). However, the live demo seems to be fine. How?

    Thanks.

  37. anoniem
    anoniem says:

    Dear Mike, thanks a lot for this tutorial. I have one question. Is it also possible to let people react to an event from your website. I want the option that people can give up their RSVP from my website, so they don’t have to go to Facebook.

    Kind regards, dennis

  38. vitthal
    vitthal says:

    Hi Mike,
    I have a question for you.
    Instead of Facebook Pages, Can we create and export events from a Facebook Application?
    I had created an app in Facebook, and I want to create/export events from facebook to my website and also from my website to facebook app.
    Is this possible?
    Please Help!

  39. Barry
    Barry says:

    Thanks for the script! This is a huge time saver! Unfortunately, I am having trouble with calling the venue. I have added venue to the SELECT query. When I call it by using echo $value[‘venue’]; it returns “array”. When I call the city with echo $value[‘city’]; nothing is returned. HOWEVER, other queries work perfect (name, description, start_time, and location).

    Not sure if this is from how I am creating the event? I am tagging a business in the “where” field when I create the event. The address shows in the event, but it will not let me get the city and state.

    I’m new to all of this; sorry if this is a stupid question. :(

    Any suggestions?

  40. Maulik Suchak
    Maulik Suchak says:

    Hello Mike,

    I really neeed your help man!

    In your Photo Album post, I am getting following error,

    Please help me to solve it…

    Fatal error: Uncaught Exception: 102: Session key invalid or no longer valid thrown in /Applications/XAMPP/xamppfiles/htdocs/facebook/fb-sdk/src/facebook.php on line 515

    [email protected] is my email ID. Please some one help me to solve it.

    • Nick Betting
      Nick Betting says:

      Hi Tom,

      I see you got it working on your website. Mind sharing your code? I’m using it for a Dutch website and the date and time is just messed up. The date says Wednesday, December 31, 1969
      10:00 – 4:00 pm and I’ve tried any fixes for it posted on here. As you’re Dutch too, did you edit anything specifically?

  41. Michael
    Michael says:

    For the Problem with 31 December …. copy the following code to your Index.php
    and change your date_default_timezone_set…

    $start_date = $values[‘start_time’];
    $timestamp = strtotime($start_date);
    $start_date = date(“d.m.Y”, $timestamp);

    $start_time = $values[‘start_time’];
    $timestamp = strtotime($start_time);
    $start_time = date(“H:i”, $timestamp);

  42. Nele
    Nele says:

    hi mike – great script but there is a solution for the timezone
    problem? the note on the fb developerpage does not bring me more, im not
    a programmer ;-( for example: im setup following data (see attachment)
    the result is – on Thursday, January 01, 1970 – 1:33 am to 1:33 am –
    see on pocuca.com/fb
    many many thanks in advance

    • Mike Dalisay
      Mike Dalisay says:

      Hi Sebastian, you can append limit 0,3 to the query to limit results to 3 events.

      Maybe you can limit the description to 15 words by doing $descriptionArr = explode(” “, $description); and then loop through it to get the first 15 items (words) to compose the 15-word description.

  43. Stephan
    Stephan says:

    All works, but above the events i get the following code. What does this mean?

    Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /kunden/webseiten/stephan/contao/facebook/index.php:47) in/kunden/webseiten/stephan/contao/facebook/fb-sdk/src/facebook.php on line 49

  44. $53577695
    $53577695 says:

    Hello Mike

    Thank you for your examples!

    I recently used your example for load photos from Facebook using my app id and secret, and it works on any page (even if mine or not) i proved.

    Now, i proved this code on two pages: COAN-Dummy-Page and AwenMasajes (my own page), but this code works only on your page, using my app id and secret.
    I don’t understand what is access token, what is the difference between that and my app id and secret.

    Do you have any idea of what i have to do?

    Thank you very much, again.

    (sorry for my poor english)

      • $53577695
        $53577695 says:

        That’s what i did. But your code olny works on the fanpage COAN-Dummy-Page and doesn’t work on my fanpage AwenMasajes. I don’t know what is the difference betweeen them. What i have to do with my fanpage? The code is the same, only change the fanpage’s id.

  45. simonerama
    simonerama says:

    Hi Mike,
    Only one thing, I suggest to convert the date in PHP as follows:

    $starttime = ”.$values[‘start_time’].”;
    $st = new DateTime($starttime, new DateTimeZone(‘PST’));
    $st -> setTimezone(new DateTimeZone(‘CET’));

    Echo:
    format(‘d-m-Y H:i:s’); ?>

    To avoid the PHP error “A non well formed numeric value encountered”.

    Btw amazing tutorial.

  46. Spilab
    Spilab says:

    Hi

    i have created the app as you described and coiped the app id and secret to the index.php. I filled in my uid and tried it on my web with no success. i don´t get any errors, the web is just all white and blank.

    My webhost runs php “Version: 5.2.10-2ubuntu6.10” and i copied all the other files in same structure you described.
    Do i have to prepare the app with permissions, other details to be able to read from my events_menber db?
    Regards
    Uffe

  47. click_wrrrrr
    click_wrrrrr says:

    Interesting Error…
    this error occurs right out of the box on set up.
    Everything else is fine, but that is an annoying error.

    Undefined variable: prev_button in pull-facebook-datapull_fb.class.php on line 151

  48. MayJuly Hlwan MoeThu
    MayJuly Hlwan MoeThu says:

    Hello,

    what wrong on me?
    //////
    Warning: session_start() [function.session-start]: Cannot send session cookie – headers already sent by (output started at /home/asiaterm/public_html/index.php:8) in /home/asiaterm/public_html/fbsdk/src/facebook.php on line 49

    Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /home/asiaterm/public_html/index.php:8) in /home/asiaterm/public_html/fbsdk/src/facebook.php on line 49

    This event list is synchronized with this mypage |

    Fatal error: Uncaught Exception: 190: Invalid OAuth access token signature.
    thrown in /home/asiaterm/public_html/fbsdk/src/base_facebook.php on line 1271
    /////

    error on my site , how to fix them ? pls help me

  49. Dave
    Dave says:

    Mike,

    I wanted to know if you knew of a way to display a url in the event description on Facebook as a link in the event description on the webpage? Any thoughts?

    Thanks in advance.
    Also great tutorial!

  50. pigsound
    pigsound says:

    hi mike,
    i’ve been trying to make your code run on my website without for several hours without any success. i set up your files, changed the IDs to mine, but when the page loads, it only shows the html part of your script.
    can you tell by this little information where i could have made a mistake?
    thanks in advance, pixie

  51. pigsound
    pigsound says:

    hi mike,
    still trying to solve the problems i’m stuck in:
    i uploaded your scripts to another server (no test server!) and it still doesn’t work. but now i at least get some error codes:

    with “facebook-event-to website” i get:

    Fatal error: Uncaught CurlException: 28: connect() timed out! thrown in /cluster/www/mydomain.com/facebook-event-to-website/fb-sdk/src/base_facebook.php on line 994

    with “pull-facebook-data/show_events.php” i get:
    Fatal error: Uncaught CurlException: 28: connect() timed out! thrown in /cluster/www/mydomain.com/pull-facebook-data/fb-sdk/src/base_facebook.php on line 886

    what am i doing wrong?

  52. Guest
    Guest says:

    I keep getting this error message, even when changing nothing on your example index.php:

    Warning: session_start() [function.session-start]: Cannot send session cache limiter – headers already sent (output started at /home/twofr0/public_html/bands/theunicornz.com/new/events.php:47) in/home/twofr0/public_html/bands/theunicornz.com/new/fb-sdk/src/facebook.php on line 49

    I am stuck at this point and could use any help in figuring it out.

    The test page is:http://theunicornz.com/new/events.php

  53. KB
    KB says:

    Question: My site is not pulling the correct dates and times. It is showing Wednesday, December 31, 1969 at 4:33 pm — Do you have any experience with why that might happen? Is that a default/fallback date? Can I share our test link directly with you for assistance? Thanks

  54. Jens Bergander
    Jens Bergander says:

    I have problems with the date.

    Whatever I do, I will get a wrong day, wrong month and wrong year.
    I.m from Germany Berlin.

    What should I do?
    I tried: date_default_timezone_set(‘Europe/Berlin’);

    :-(

  55. Jens Bergander
    Jens Bergander says:

    Hi,

    i have some problems with the date.

    Whatever I do, I get incorrect date

    wrong day, wrong year.

    i try to change my timezone
    date_default_timezone_set(‘Europe/Berlin’);

    and what i do, i get a wrong date.

    what can i do?

  56. *Luis*
    *Luis* says:

    Hi Mike,

    just discovered this great script and have it up and running on the following testpage:

    http://mitcas.de/fbtest/

    The problem i see is that the description of the event doesnt get formatted the way it is on the facebook fan page.

    For example here: https://www.facebook.com/events/529085623825726/

    you get this:

    —————————-
    “Einlass : 19 Uhr
    Beginn : 20 Uhr
    VVK: http://www.gibson-club.de/de/tickets

    Erst einmal ist da diese Stimme… großartig und schillernd wie er auf der Stimmpalette tanzt. Von krä…..”
    —————————-

    But on the above testpage with your unmodified script you get all text in one line…:

    —————————-
    “Einlass : 19 Uhr Beginn : 20 Uhr VVK: http://www.gibson-club.de/de/tickets Erst einmal ist da diese Stimme… großartig und schillernd wie er auf der Stimmpalette tanzt. Von kräfti…”
    —————————-

    How can we fix that? Seems like your script is not reading the breaks from the event-description.

    THANK YOU SO MUCH FOR YOUR HELP! :-)

  57. Nick
    Nick says:

    THANK YOU so much for all your work on this and other tutorials. Is there any way to also have the text for the events hyperlinked to the actual event pages??? Thanks again!

  58. KT
    KT says:

    For anyone having problems with the date showing up like a default date (1969 or 1970), try this:

    Inside the App dashboard click App Settings > Advanced. Set the ‘Events Timezone’ to disabled.
    It is enabled by default. If enabled timestamps are ISO-8601. This does not work with this PHP code.

  59. Hendrik Veeman
    Hendrik Veeman says:

    I am no PHP or JS programmer and am trying to get the website I uphold for the owners up to date.

    The owners of the cafe put the events on their Fb account, and i am now trying to implement it into their site http://www.cafetsjoch.nl

    I haven’t got much luck so far getting it integrated. Something is somewhere getting it wrong but I don’t know where and why.

    the test page is: http://cafetsjoch.nl/fbevent.html

    My first attempt was http://cafetsjoch/test.html but it was blank in whatever i tried.

    As you can see at the site i use i-frames and ajax-files
    Hopefully anyone can help me.

  60. Radek Cichocki
    Radek Cichocki says:

    Two things I don’t get.

    1) The UID here is hard coded. When I change it to mine or to one of my friends’, I get zero results. Why?

    2) How come you don’t need to be logged in first for it to work?

      • Radek Cichocki
        Radek Cichocki says:

        Thanks for your reply!

        That explains it. I am wondering… If I wanted to get events that were posted to an open, public group (not fanpage):

        1) Would I still not need to log in?
        2) How would I need to change the FQL query to do that? (I’m new to Facebook apps)

  61. Bas Koole
    Bas Koole says:

    Hi Mike, thanks for the great script. I’m a programming novice, but got this running the way i wanted to pretty quickly. I’ve got one thing i couldnt figure out: I would like to use setlocale() to show the weekday in dutch. Could you elaborate how i can implement this in your script? Thanks in advance, i owe you a beer.

  62. treps_92boy
    treps_92boy says:

    Hi Mike,
    First, thanks for this amazing tutorial. I’ve just got a tiny little problem. Today’s event doesn’t appears. At 00:00 the same day as the event it disappears from the site. Any idea how I can fix it?
    Thanks in advance.

  63. troppic_burrito236
    troppic_burrito236 says:

    Hi
    I successully got this example working with my own fan page however the time and dates are different from those of the actually events on my fanpage. I changed the time zone in the code but this doesn’t fix this. Any suggestions?

  64. Dan Cooprider
    Dan Cooprider says:

    Mike, Im new to web design…. really I am a 3D VFX artist trying to pay the bills with web-design. Sadly I am not much of a code person yet. Now, one thing i am getting is that people want to embed or stream their facebook events page to their website. I have created an App ID and App Secret… now what am I doing wrong with your code in this example. I am using Adobe Muse as my web building tool, any help would be appreciated.

  65. n0fear
    n0fear says:

    If anyone elese got the 01.01.1970 Problem. Changing

    $start_date = date( ‘l, F d, Y’, $values[‘start_time’] );

    to

    $start_date = date( ‘l, F d, Y’, strtotime($values[‘start_time’]));

    did the trick for me. Thanks for this nice script!

  66. n0fear
    n0fear says:

    Hi together, i am a real beginner in coding, is it possible to link the Title to the facebook event als an URL? So if someon clicks on the title he gets new page opend with the event? How would i do that?

  67. joomsch
    joomsch says:

    I think i do have a problem with my app. I always get “Restricted access” at my page. Do I have to set some settings in my App to get access ?

  68. Sergio
    Sergio says:

    Hello and THANK you this this amazing work! :) I still have a problem… I did the proper replacement —-$start_date = date(‘l, F d, Y ‘, strtotime($values[‘start_time ‘]));—- and I have the data showing as 31 December 1969! :( What is wrong? Anyone can Help? Thanks

  69. Paul
    Paul says:

    Hi, it is very great tutorial but I faced with problem that I can’t solve, I tried to launch my page with my app id and secret and with my page id but I got this: http://vivaretro.hol.es/event/ just everithing goes blank

    here is the code:

    Display Facebook Events to You Website

    ‘331817830310323’,

    ‘secret’ => ‘4b90b95abc7c3e3a0c68f4f583982911’,

    ‘cookie’ => true

    ));

    /*

    *-Query the events

    *

    *-We will select:

    * -name, start_time, end_time, location, description

    * -but there are other data that you can get on the event table

    * -https://developers.facebook.com/docs/reference/fql/event/

    *

    *-As you will notice, we have TWO select statements here because

    *-We can’t just do “WHERE creator = 132064480282039”.

    *-Only eid is indexable in the event table

    * -So we have to retrieve list of events by eids

    * -And this was achieved by selecting all eid from

    * event_member table where the uid is the id of your fanpage.

    *

    *-Yes, you fanpage automatically becomes an event_member once it creates an event

    *-start_time >= now() is used to show upcoming events only

    */

    $fql = “SELECT

    name, pic, start_time, end_time, location, description

    FROM

    event

    WHERE

    eid IN ( SELECT eid FROM event_member WHERE uid = 221167777906963 )

    AND

    start_time >= now()

    ORDER BY

    start_time desc”;

    $param = array(

    ‘method’ => ‘fql.query’,

    ‘query’ => $fql,

    ‘callback’ => ”

    );

    $fqlResult = $facebook->api($param);

    //looping through retrieved data

    foreach( $fqlResult as $keys => $values ){

    /*

    * see here http://php.net/manual/en/function.date.php

    * for the date format I used.

    * The pattern string I used ‘l, F d, Y g:i a’

    * will output something like this: July 30, 2015 6:30 pm

    */

    /*

    * getting start date,

    * ‘l, F d, Y’ pattern string will give us

    * something like: Thursday, July 30, 2015

    */

    $start_date = date( ‘l, F d, Y’, $values[‘start_time’] );

    /*

    * getting ‘start’ and ‘end’ time

    * ‘g:i a’ will give us something

    * like 6:30 pm

    */

    $start_time = date( ‘g:i a’, $values[‘start_time’] );

    //printing the data

    echo “”;

    echo “”;

    echo “”;

    echo “”;

    echo “”;

    echo “{$values[‘name’]}”;

    /*

    * -the date is displaying correctly, but the time? uh, sometimes it is late by an hour.

    * -it might also depend on what country you are in

    * -the best solution i can give is to include the date only and not the time

    * -you should put the time of your event in the description.

    */

    echo “{$start_date} at {$start_time}”;

    echo “{$values[‘location’]}”;

    echo “{$values[‘description’]}”;

    echo “”;

    echo “”;

    echo “”;

    }

    ?>

    I tested to comment some rows and it seems like problem appears when php comes to this row:
    $fqlResult = $facebook->api($param);

    Do you have ideas why it is so?

    • ninjazhai
      ninjazhai says:

      Hey @Paul, there are some change in Facebook’s system right now, I will update his post asap. I think that is what’s causing the problem. Please connect with us via FB or twitter for the updates, thanks!

  70. Nicolas Leitgeb
    Nicolas Leitgeb says:

    Hey Mike, i hope this is still working in general and you can help me. I wanted to integrate this into my homepage but it doesnt work, so i tried it standalone but i only get a blank site with the header… whats wrong there, i used ur code here and did every step very carefully…

    • ninjazhai
      ninjazhai says:

      Hello @nicolasleitgeb:disqus, I think there are some changes in Facebook’s system right now. I will have to update this article asap. Keep up with the updates by connecting with us via facebook or twitter, thanks!

  71. ninjazhai
    ninjazhai says:

    Hello everyone! I updated the source code and tutorial again (September 3, 2014), I did not use the FB PHP SDK this time. Please let me know if there’s any issue, we’ll look into it, thanks!

    • ninjazhai
      ninjazhai says:

      You’re welcome @paulmintskovsky:disqus, thanks for using our code here! Regarding your issue, your code looks fine, it’s hard to find out what’s the error if it has no error message… would you try to paste your fb page id?

      • Alan
        Alan says:

        It’s weird though because his live demo is still working.. I’ve added more functionality to my site and now this is the last thing to do.. He uses FQL in this, isn’t this depreciated unless your facebook application was created months ago?

        • ninjazhai
          ninjazhai says:

          Hello @disqus_Jqj3qiit9f:disqus and @Alan, are you using PHP 5.4+? Would you put error_reporting(E_ALL); at the beginning of your PHP file so that we can see any error message, and tell us here. Thanks!

          • Philippe
            Philippe says:

            I’m using PHP version 5.3.29
            and have the following error message:

            file_get_contents(https://graph.faceb….AYB6EeQ): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/dice…e/event2.php on line 57 Notice: Use of undefined constant JSON_BIGINT_AS_STRING – assumed ‘JSON_BIGINT_AS_STRING’ in /hom…ource/event2.php on line 59 Warning: json_decode() expects at most 3 parameters, 4 given in /home/dicetat…k-feed-source/event2.php on line 59

            thanks for your help

          • ninjazhai
            ninjazhai says:

            Would you guys try to use:

            $obj = json_decode(preg_replace(‘/(“w+”):(d+)/’, ‘\1:”\2″‘, $json), true);

            instead of:

            $obj = json_decode($json, true, 512, JSON_BIGINT_AS_STRING);

          • Philippe
            Philippe says:

            Only 1 error now.
            failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request
            in /ho..ent2.php on line 55

            line 55 has: $json = file_get_contents($json_link);

          • ninjazhai
            ninjazhai says:

            The value of your $fql looks weird, why does it have a lot of ‘+’ characters: q=SELECT%0A++++++++++++eid%2…

          • Rachel
            Rachel says:

            Hi. Thank you for the tutorial!
            Was this issue resolved? I am getting the same error (online).
            Thanks–

            Warning: file_get_contents(https://graph.facebook.com/ …. [function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in … on line 32

            (Using $obj = json_decode(preg_replace(‘/(“w+”):(d+)/’, ‘\1:”\2″‘, $json), true);)

          • Mike Dalisay
            Mike Dalisay says:

            @disqus_67ugo85UD5:disqus, yes that issue can be solved easily, you maybe have a wrong graph API url or access token, or your server is rejected by Facebook due to high amount of request (problem with shared hosting). Would you give us your test URL?

          • Alan
            Alan says:

            Also this is probably a stupid question but I’ve never used php before – how do I check which version I’m using? I’ve only recently installed it so I’m assuming I have the latest version

  72. Nicolas Leitgeb
    Nicolas Leitgeb says:

    Hey Guys,
    is it possible to display events of more than one site in one table/list e.g. for band agencies who want to display upcoming events of bands they support…

  73. Rook
    Rook says:

    This works for page events but not events based on a profile. This is the error: Warning: json_decode() expects at most 2 parameters, 4 given. Do you know how to make this work with profiles.

  74. bob holling
    bob holling says:

    Hi there…question: do you know if your method works with age-restricted content? A friend has a liqueur business and would like to post his tasting events from FB to his WordPress website. All attempts thus far have failed due to FB’s policies on age-restricted content, so wondering if your solution would solve for that. Thanks!

    • ninjazhai
      ninjazhai says:

      Hello @bobholling:disqus, in this case, I believe Facebook would allow us to pull publicly available data only. No any kind of restriction such as the age-restricted content.

      But I haven’t really tried any workaround on that, maybe it’s possible now but I don’t know how to do that yet.

  75. Laurent Loiseau
    Laurent Loiseau says:

    Hi

    Awesome tutorial. Almost everything works well for me. I just had to change the variable $fields. Facebook says fields “location” and “venue” are deprecated. I replaced it by the field “place” :) Then, you can display the following fields :

    “place”: {
    “name”: “LA SOUTE”,
    “location”: {
    “city”: “Chambu00e9ry”,
    “country”: “France”,
    “latitude”: 45.568758364409,
    “longitude”: 5.916880680781,
    “street”: “Citu00e9 des arts jardin du Verney”,
    “zip”: “73000”
    },
    “id”: “175714291355”

    Thanks a lot for sharing your experience ! (and sorry for my poor english ;) )

  76. menathor
    menathor says:

    Awesome work Mike- great to see the new version using the Graph API!

    One thing though- I noticed the same timezone problems as the fql version. You can see it on the demo of the pro version- just check out the date and time displayed on your page for some of Ed Sheeran’s events and compare them to the date / time of the actual Facebook event. You’ll notice that they’re different because you’re in a different timezone.

    I corrected this in the old version by setting the date_default_timezone_set() value for each individual event to the timezone value of that event. Could you add this fix to the new code as well?

    • Mike Dalisay
      Mike Dalisay says:

      Hello @menathor:disqus, sorry for the late reply. You’re correct, for others who are reading, please add the following code inside the ‘for’ loop (see step 11 above)

      date_default_timezone_set($obj['data'][$x]['timezone']);

  77. Vanessa Keeton
    Vanessa Keeton says:

    How do I change the order of the events? Currently the most future date is showing first in the list. I need them to be in event date order.

    –Update: I did a little research and it seems there isn’t a what to change the order of items in the graph API, so I sort of combined your older FQL version of this with the newer version. It works fine now, since I can change the order from the query. I also think that this wouldn’t work if I had not already created the app before the Graph API was released and I am not sure if FB will just break this sometime soon. But for now, at least it works.

    If you know of a way to do it with the graph API, I’d still love to know it.

    Thanks for sharing your code! I was happy to buy it the second time around because it is very useful for my clients. :)

    • Mike Dalisay
      Mike Dalisay says:

      Hello Vanessa Keeton, unfortunately, Facebook API does not give us the ability to sort the order of events, but I made a workaround for it. Use the following before the ‘for loop’ code:


      function sortFunction($a,$b){

      if ($a['start_time'] == $b['start_time']) return 0;

      return strtotime($a['start_time']) - strtotime($b['start_time']);

      }

      usort($obj['data'],"sortFunction");

      The only disadvantage is that, it will only sort the currently loaded JSON content.

      Thanks for the kind words and sorry for the late reply…

      • Vanessa Keeton
        Vanessa Keeton says:

        Thanks for the reply! I’ll give this a try next time I am making an update to the site or if I use this on another. :) Thanks again for sharing your ninja skills.

  78. Thomas Bloom
    Thomas Bloom says:

    First of all thanks for the excellent tutorial, I already successfully used this code on 1 website. I am running into an issue with the second website I am working on.

    The issue that I am having is that I cannot display the most recent events from my facebook page but can only show events from 2011?

    I have echo’d the since_date and since_date variables to ensure that the dates are correct but no matter what I do I cant get events to show, only events that happened a long time ago in 2011. Is there a limit to the number of events the application can pull?

    I have a feeling this is a facebook issue and not an issue with the code but any insight would be appreciated.

    • Mike Dalisay
      Mike Dalisay says:

      Hello @disqus_0d0j4DwshJ:disqus, thanks for the kind words! I’m glad it worked on your website. About your concern, this is a new report, what we usually encounter is the events from 2012 does not show. Would you link us to your Facebook page and test URL so we can investigate more?

  79. fusil
    fusil says:

    You can take a look here https://github.com/newbacknew/owloo.com. This is a base of scripts from http://www.owloo.com for get data from Facebook via the “ADS” Dashboard, also have to retrive analytics data from Twitter and Instagram.

    With the base script you can get trends, interests, behavior, demographic, ages, gender qty of every country, city, stage, fanpage from facebook.
    The base of all script are in the WSERVICE folder of the backups folders.

  80. Bisento
    Bisento says:

    Thanks for the tutorial. I wasn’t able to make the code work until I found that I had to remove brackets in step 8 Json link. Thought this might help others in the same situation. Cheers

      • Bisento
        Bisento says:

        I put them back and it works nice finally, I wasn’t aware of the “{$var}” syntax so I might solved another error while changing it to ‘.$var.’ sorry for wasting your time.

        I’m currently looking for a way to show events created by users but it seems I need a user access token or something, could you point me some places to look at please ? I’d like to make an upcoming concert list from multiple promoters (pages and users), it works fine with pages as you can see here : http://www.bisento.fr/

        • Mike Dalisay
          Mike Dalisay says:

          @disqus_7Q6D0fzAdH:disqus, your were able to display events from multiple fb pages, that’s cool! But were you able to add an ‘infinite scroll’ feature? About events created by users, yes I think user access token is needed for everything created by users. I haven’t tried to play around with that so I can’t really give a good reference for you..

      • Daniel Mort
        Daniel Mort says:

        Just wanted to say thank you. Just purchased the script pro pack today not too long ago and modified it a bit to make it a dark theme and it’s working great. It took a little bit figuring out how to style each individual element, but I have a basic idea now. In any case, it saved me A LOT of time! I read something about having to get an access token from Facebook? Well I just changed the pageid and it seems seems to work. What will i need the access token for? And lastly, is there a place to change pageid and access token globally, or do I have to change it on each page? Thank you!!!!!!!

        • Mike Dalisay
          Mike Dalisay says:

          Hello @daniel_mort:disqus, thanks for purchasing the source codes! We are glad you found it useful and saved you a lot of time.

          About your questions, yes it will work with the current access token, but it is more recommended to use your own access token. See the step 7 on how to obtain your own access token. One advantage of having your own access token is, you won’t be affected just in case the current access token had problems.

          About global page ID and access token, currently, you have to change it by page, but we’ll change it in future updates. For now, you can use PHP includes or sessions so it can function like a global variable.

      • Daniel Mort
        Daniel Mort says:

        Okay, one last question. How do I sort the events from most recent to farthest away? Upcoming events and all events in particular. Past event’s tab seems to be in the correct order, but there’s only 5 showing of 50+ past events. no page 2 or anything.

  81. Hans Blaettler
    Hans Blaettler says:

    Hi, great script! But one question: my sitemap generator keeps adding pages because of each upcoming month, although $year_range = 1; and it won’t quit generating because of all the years ahead ;-) Please advise what to do so I can update my sitemap? #thanx

  82. Valeria
    Valeria says:

    Hello,

    We are looking for a way to retrieve the list of event attendees from Facebook. Ideally, if the attendee has an account on our site (given that he signed up with Facebook), he should be recognized as a user, so we can use this information for the loyalty program. We are using WordPress.

    I’ve been searching for a while already, and none of the available solutions gives the option of retrieving/importing the attendee list. I’m not familiar with the Facebook API and it’s hard for me to imagine what would it take. Could you advise on that?

    Also, would you be interested in developing a plugin like that (or rather a customization to an existing plugin that imports events)?

    Thank you.

  83. Ori V Agmon
    Ori V Agmon says:

    Hello thank you SO MUCH for this helpful information.
    _
    THERE is a way to pick the specific events from my facebook acount, that I want to be shown on this tool?

  84. suthemeny
    suthemeny says:

    Hi! I really like this solution to display events on my website!

    I’m a little bit confused… I’m wondering how to define to display only the next 3 events… I made a loop, but if I don’t have 3 upcoming events, only 1 or 2 it displays blank rows with the page profile picture as event image, what I don’t need…

    My loop is:
    for($x=0; $x<3; $x++){
    // here comes the table…
    }

    What I want is to display only the row(s) that have real content.

    Thank you!

  85. Nicolas
    Nicolas says:

    Wow … I was looking to finally do that and It took me few hours to understand facebook doc. Now with your website, it took me 10 min. Thank ! It was very easy to do it and to understand !

  86. dorisweldonkaz
    dorisweldonkaz says:

    I just wanted to thank you again for both the code and for your help! My husband says we owe you a beer! Brilliant work and a very kind person. Thanks again.

  87. Marouan
    Marouan says:

    Hello, thnks for your Doc, its very Interessant and i have used. So, my question is, i want to get all FB Events with Tags or Cateroy . But i dont have any information im internet finded.
    For example :
    Event Name : ABCD
    Start Time : 10.07.2016
    End Time : 13.07.2017
    Interessed : 120 Person
    Category : Musik
    Tags : musik, sport, halloWorld,..
    etc…

    Plz, have you any Idee ? Thnk you very much

  88. BigTonyTheNinja
    BigTonyTheNinja says:

    Greetings! Thanks for this script. It has been very helpful. I have set it up on a website for a music venue. It displays upcoming events and I am using the re-order script to display them in order from the most imminent. It seems that it is starting with events that are two weeks away instead of displaying the events closest to today’s date. I am using the script in two places on the site. On the Home page and on the Events page. Any thoughts on this? I assume it has something to do with the json data grab.
    Here is the website and its corresponding facebook page:
    http://www.lamascobarandgrill.com
    http://www.lamascobarandgrill.com/events
    https://www.facebook.com/lamascobarandgrill

  89. Akeem Sca
    Akeem Sca says:

    Hi Mike, thanks for the amazing tutorial! I’m just wondering how long the access_token (described in 9.0) will last?! Is it hours, days, months or do these have unlimited lifetime?

  90. Daniel Fernandes
    Daniel Fernandes says:

    hi! Thank you so much for this amazing tutorial!!!
    But how can I change the language? Like its “Wednesday, March 27, 2013 at 12:00 pm” and i want that on portuguese :/

  91. Dustin Rogers
    Dustin Rogers says:

    Hey there, I could use some help with this… The code works great, and Ive used it on sites before, but the problem I am having now is that the code doesnt work with this one Facebook page I use. It works for all other Facebook pages I try except this one. Is there a setting within Facebook pages that prevents this code from working?

    • Mike Dalisay
      Mike Dalisay says:

      Hello @disqus_fy32CWCXA4:disqus , would you post the link of your Facebook page? Page must be publicly available, please check if your page has something like age restriction. If there is, try to remove it and try again.

  92. Dominik Waitzer
    Dominik Waitzer says:

    It works fine but it just show me events which starts from 24th of Mar. 2017 – I’ve tried everything I think, but it’s not possible to show me all events which starts from tomorrow. Help?

  93. Jonas Niedermair
    Jonas Niedermair says:

    Hello @ninjazhai:disqus the code is great! But do you have an idea how I can save the description of a facebook event in my MySQL database if the text of the description includes special chars like ❤ , • …
    I have already tried to convert the string with html_specialchars but it doesn’t work..

    Thanks for your help !:)

  94. Ramon Strapatsen
    Ramon Strapatsen says:

    Hi,

    It works, but it didn’t show all the events. Some events aren’t show on the website.
    All the events are public and events hosted with more admin are loading also..

    I also checked it with the demo’s (changed the page_id in the link) it didn’t load.

    What could be the problem?

  95. Michelle Currier
    Michelle Currier says:

    Is anyone gettting an error on the this line:
    $json = file_get_contents($json_link);
    It worked for me a few weeks ago last time I checked my site but now I have this error.
    My site is djnicerack.com/events.php

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.