1

I've tried to move a php array to a javascript array. this is what I did:

$cities = "בני ברק, גבעתיים, חוות שלם, רמת גן";

$php_array = explode(',', $cities);

$js_array = json_encode($php_array,JSON_HEX_APOS|JSON_HEX_QUOT);

echo "<script type='text/javascript'> var cities = ". $js_array . ";</script>";

for some reason, when I open the google chrome debuger, and check what cities is, this is what I get:

<script type='text/javascript'> var cities = ["&#1488;&#1494;&#1506;&#1511;&#1492; &#1489;&#1489;&#1504;&#1497; &#1489;&#1512;&#1511;"," &#1490;&#1489;&#1506;&#1514;&#1497;&#1497;&#1501;"," &#1495;&#1493;&#1493;&#1514; &#1513;&#1500;&#1501;"," &#1512;&#1502;&#1514; &#1490;&#1503;"];</script>

I don't know why it's decoding. I have php 5.6.

Later I tried just moving a normal variable and even when I move a normal variable (without json_encode) it becomes like that

I used those examples:

Convert php array to Javascript

Passing utf-8 strings between php and javascript

Thanks!

Community
  • 1
  • 1
morha13
  • 1,847
  • 3
  • 21
  • 42

1 Answers1

4

First, save your file with UTF-8 with BOM encoding. Then, add the JSON_UNESCAPED_UNICODE option to your json_encode call.

$js_array = json_encode($php_array, JSON_HEX_APOS|JSON_HEX_QUOT|JSON_UNESCAPED_UNICODE);
blex
  • 24,941
  • 5
  • 39
  • 72
  • For some reason I get the same result.. The file is saved in UTF-8 with BOM – morha13 Jul 16 '15 at 21:22
  • @MorHaviv Oh, it works for me... hmm, I'll keep looking. – blex Jul 16 '15 at 21:23
  • @MorHaviv No, that should not change anything. Just in case, try pasting **[just this code](http://pastebin.com/embed_iframe.php?i=4gSLLuxU)** in a new `UTF-8 with BOM` encoded php document. Then, visit it and view the source (don't use the debugger, which can sometimes modify the code received). Do you still get that problem? – blex Jul 16 '15 at 21:27
  • It is working but now I found the thing that causes the problem. Basically the $cities var is recieved by post. I just put an example of the data can be received. `$cities=_$POST['cities'];` When I do echo $cities it looks normal, but when it goes in to json_encode it becomes decoded – morha13 Jul 16 '15 at 21:33
  • @MorHaviv Well, this works for me... http://pastebin.com/embed_iframe.php?i=bZUprxb6 If you still have the problem with your code, maybe giving your full page script would help, actually. – blex Jul 16 '15 at 21:46
  • 1
    I marked you answer as correct because it is correct for the question I asked. I should have asked another question since the problem is with the post method I used. well anyways thanks to you I found the real problem and solved it! Thank you! – morha13 Jul 16 '15 at 21:48