Reputation: 9658
I'm looking for the best way to escape some Javascript text in PHP, and json_encode
is the wrong tool for the job.
The problem comes from this line:
If there's an apostrophe in
echo " onclick=\"SwitchDiv('" . $option . "')\"";
$option
, this is a juicy ball of client-side fail. But doing a straight json_encode
(which works perfectly well in other contexts) doesn't help:
That creates an output string of
echo " onclick=\"SwitchDiv(" . json_encode($option) . ")\"";
onclick="SwitchDiv("athlete's foot")"
, resulting in premature termination of the onclick
value. (Which also happens if I enclose the onclick
value in single quotes.)
Is there an elegant way around this? Should I just funnel the json_encode
output through a regex that will escape the single quotes?
Upvotes: 0
Views: 90
Reputation: 43158
json_encode
is the right tool for the job. Your problem arises from the fact that you are also including that Javascript in an HTML attribute, thus it also needs to be htmlspecialchars
-encoded.
echo " onclick=\"SwitchDiv(" . htmlspecialchars(json_encode($option)) . ")\"";
Upvotes: 3