Criesto Criesto - 4 months ago 32
Javascript Question

Extracting page id from a facebook page url

I have an application where when a user enters their facebook fan page url, I extract the page id and store that into the database to be used later in facebook graph api.

I have added the following js to extract page id:

<script>
var fburl= "https://www.facebook.com/audi";
if(fburl.indexOf("?") != -1) {
var fburl_new=fburl.split("/");
var fburl_newer=(fburl_new[fburl_new.length-1])
var fburl_newer =fburl_newer.split("?");
var fbnameonly=(fburl_newer[fburl_newer.length-2]);
} else {
var fbnameonly = fburl.substring(fburl.lastIndexOf('/') + 1);
}
if(fbnameonly==undefined) {
console.log(fburl);
}else {
console.log(fbnameonly);
}
</script>


So, if I a user enters a facebook url like:
https://www.facebook.com/audi
, I get the output
audi
which is fine.

If a user enters facebook url as :
https://www.facebook.com/pages/abc-def/1234568
, I get the output
1234568
which is fine.

but for urls like:

https://www.facebook.com/abc-def-12345678/
(should return 12345678)

or

https://www.facebook.com/audi/timeline?ref=page_internal
(should return audi)

I am unable to get the page id, is there any better way by which I can extract page id from any facebook fan page url and use it in facebook graph api like:
https://graph.facebook.com/page_id
dynamically ?

Answer

I figured out a better way to get page id from any facebook page url, I am not sure if there is even better option to do this but here is the code what I have used:

$fbUrl = "https://www.facebook.com/Lo-stile-di-Anna-1521824524722026";
$graphUrl = "https://graph.facebook.com/?id=".$fbUrl."&access_token=xxxxx&fields=id";
$output = file_get_contents($graphUrl);
$output = json_decode($output, TRUE);
echo $output["id"]; // returns 1521824524722026

I tried this with various facebook urls and it worked everytime, hope this helps someone in the future.