Search code examples
phpjavascriptfacebookdialogfeed

Populate Facebook Feed Dialog from SQL database


is it possible to populate Facebooks Feed Dialog dynamically with PHP variables fetched from an SQL database in a safe way?

    ...
    // calling the API ...
    var obj = {
      method: 'feed',
      redirect_uri: 'YOUR URL HERE',
      link: 'https://developers.facebook.com/docs/reference/dialogs/',
      picture: 'http://fbrell.com/f8.jpg',
      name: 'Facebook Dialogs',
      caption: 'Reference Documentation',
      description: 'Using Dialogs to interact with people.'
    };
    ...

I guess that for example:

    name: '<?php echo $name; ?>', etc..

should be possible..but what if the name contains an ' character? Same thing with the descrption since that will likely consist of different special chars that might break the javascript code.

How can i avoid this or is there a "pure" php based method to fill an Feed Dialog with database content as images, name, description and so on..


Solution

  • You want to produce a javascript object, the easiest way is to use json_encode(), which will take care of all the escaping for you:

    <?php
    $fb_feed = array(
      'name' => $name,
      'method' => 'feed',
      ...
    );
    ?>
    var obj = <?php echo json_encode($fb_feed) ?>;
    

    Note that if for some reason you don't want to produce your whole object like that, you can also use it with a single field:

    var obj = {
          method: 'feed',
          name: <?php echo json_encode($name) ?>,
          ...
    }