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!

1
  • That's how json_encode handles unicode characters... Commented Jul 16, 2015 at 21:19

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

6 Comments

For some reason I get the same result.. The file is saved in UTF-8 with BOM
@MorHaviv Oh, it works for me... hmm, I'll keep looking.
@MorHaviv No, that should not change anything. Just in case, try pasting just this code 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?
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
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!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.