2

I was trying to get away from using PHP's htmlentities and here's where I stopped:

<?php
echo '<img ... onclick="MP.view(\''.$i->name.'\') />';
?>

But then I thought, instead of doing replaces and checks for special characters, I'll just JSON the entire object.

<?php
echo '<img ... onclick="MP.view('.json_encode($i).') />';
?>

And this provided a much undesired result putting in a ton of double quotation marks. So how should I do this? Should I assign a numerical unique id to every image and just pass the id, and then look up the rest of the data from a JS array?

2
  • Why not just pass the URL of the image to view? It would help to know what MP.view does... Commented Jun 13, 2011 at 19:27
  • let's say MP.view does something rather complicated where the URL of the image plays a smaller role. Basically I need to pass a ton of data Commented Jun 13, 2011 at 20:05

2 Answers 2

6

The correct approach in such cases would be:

 htmlspecialchars(json_encode($var), ENT_QUOTES, "UTF-8")

htmlspecialchars turns any double quotes into the proper HTML escapes, making the resulting string suitable for most attributes. The ENT_QUOTES parameter also takes care of single quotes; but you probably don't need that in your example.

Sign up to request clarification or add additional context in comments.

4 Comments

then the receiving function would receive a string, no?
Ehm, no. The escaping is just for validity of the HTML attribute. So double quotes would not conflict with the DOM structure. But the JSON expression you put there can still be an object. The browser takes care to pass the original JSON/object your callback function there.
Perfect. This allows me to throw in extra information in the passed object so the function can get away with receiving just one argument
you don't need to pass UTF-8 because htmlspecialchars doens't touch non-ascii chars
0

It would take a whole lot less escaping (and fewer bytes) to pass the data something like this:

echo '<script>var myObj = '.json_encode($i).'</script>';

Then, your code could look more like this:

echo '<img ... onclick="MP.view(myObj)" />';

4 Comments

Still probably best to use htmlspecialchars in that situation, right?
@Frank: I've never needed it. You may want to wrap it in a CDATA tag, though.
@Mikhail: You can create the script in the loop, too. Just add the index to the name of the object you're creating, then use that in the onclick handler.
@Mikahi: This was merely an example. You could easily change the script content to create one variable which is an array, then use that array from your onclick handlers.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.