PHP encode JS decode

Very often I need to encode some string in PHP, then pass that to javascript. For example, say I am using PHP to generate some javascript functions. See below:

$s = "some text from somewhere";
$js_code = "
  function do_something(some_text){
    alert(some_text);
  }
  do_something('$s');
";

The above javascript code would work fine until one day you have some symbols in $s, for example the single quote. (There may be more troublemakers, but at least this is a common one).

So now you start thinking about encoding and decoding. It turns out there are so many ways to do them… Just which one do you need?

Below is my solution, you are welcome and encouraged to find your own solution.

$s = "some text !@#$%^&*()_+[]{}|;':",./?";  // of couse this is not syntactical, in reality think of this string coming from a db
$s_encoded = rawurlencode($s);
$js_code = "
  function do_something(some_text_encoded){
    some_text = unescape(some_text_encoded);
    alert(some_text);
  }
  do_something('$s_encoded');
";

Hope this can save your time. 😉

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s