SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    array: php to jscript through url

    ...and without jQuery.

    What's the best way in PHP to encode an array and pass it as a querystring var so that it can be used by a javascript (and there will be no jQuery involved)?

    My guess:

    a) json encode array
    b) base_64 encode the result
    c) url encode the whole thing

    Is there a simpler way to do it? Will my approach be ok, and the array easily retrieved with javascript (ithout jQuery help)?

    Cheers.


  2. #2
    SitePoint Enthusiast jakub_polak's Avatar
    Join Date
    Jan 2012
    Location
    Slovakia
    Posts
    35
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hello,

    you can encode the array like this:

    PHP Code:
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <?php
    $array 
    = array("žaneta""ružena""/");

    print_r($array);
    echo 
    '<br />';

    $array_encoded base64_encode(json_encode($array));

    echo 
    $array_encoded'<br />';

    $array json_decode(base64_decode($array_encoded));

    print_r($array);
    echo 
    '<br />';
    The output is:

    PHP Code:
    Array ( [0] => žaneta [1] => ružena [2] => / ) 
    WyJcdTAxN2VhbmV0YSIsInJ1XHUwMTdlZW5hIiwiXC8iXQ==
    Array ( [
    0] => žaneta [1] => ružena [2] => / ) 
    You don't need to use c) .

  3. #3
    SitePoint Zealot
    Join Date
    Jul 2011
    Posts
    199
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for your reply
    Can I be a 100% sure that base64_encode() will output characters that are not url-friendly?

  4. #4
    SitePoint Enthusiast jakub_polak's Avatar
    Join Date
    Jan 2012
    Location
    Slovakia
    Posts
    35
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by rhgiant View Post
    Thanks for your reply
    Can I be a 100% sure that base64_encode() will output characters that are not url-friendly?
    I have just realised that base64 encoded string can contain "+", "=" and "/" which could change meaning of string in URL, so you need to url encode it as well.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •