views:

109

answers:

3

I'm playing with the flickr api and php. I want to pass some information from PHP to Javascript through Ajax. I have the following code:

json_encode($pics);

which results in the following example JSON string:

[{"id":"4363603591","title":"blue, white and red...another seattle view","date_faved":"1266379499"},{"id":"4004908219","title":"\u201cI just told you my dreams and you made me see that I could walk into the sun and I could still be me and now I can't deny nothing lasts forever.\u201d","date_faved":"1259987670"}]

Javascript has problems with this, however, due to the unescaped single-quote in the second item ("can't deny").

I want to use the function json_encode with the options parameter to make it strip the quotes, but that's only available in PHP 5.3, and I'm running 5.2 (not my server). Is there a fast way to run through the entire array and escape everything before encoding it in Json? I looked for a way to do this, but it all seems to deal with encoding it as the data is generated, something I cannot do as I'm not the one generating the data.

If it helps, I'm currently using the following javascript after the ajax request:

var photos = eval('(' + resptxt + ')');  
+1  A: 

str_replace('\'', '\\'', json_encode($pics))

OIS
Hm, but what about the double quotes? I can't run the same type of replace because it would replace all of the quoted values too!
NickAldwin
A: 

You'll have to do a (recursive) foreach to walk through the array and manipulate them manually. You can do a str_replace, but addslashes works just as fine (and addcslashes is even better.)

K4emic
That's what I was afraid of (well, not afraid, but hoping there was a faster way).
NickAldwin
+2  A: 

Have you considered using JSON2 instead of eval()? Details here.

Peter Bailey
That worked. Awesome, thank you!
NickAldwin