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.

:slight_smile:

Hello,

you can encode the array like this:

<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:

Array ( [0] => žaneta [1] => ružena [2] => / )
WyJcdTAxN2VhbmV0YSIsInJ1XHUwMTdlZW5hIiwiXC8iXQ==
Array ( [0] => žaneta [1] => ružena [2] => / ) 

You don’t need to use c) .

Thanks for your reply :slight_smile:
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.