Character encoding problem in PHP/MySQL/jQuery
I made some CMS in PHP which manipulates with data from MySQL.
In my CMS, i have some input fields in which I would like to have jQuery's fancy autocomplete implemented. Basically, the idea is to create jQuery's arrays from MySQL tables...I'm working with PHP 5.3.0, MySQL 5.0.82 and Eclipse 3.4.2. My PHP project in Eclipse is UTF-8 encoded. My CMS pages are in UTF-8 character encoding (<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
). Website itself is also in UTF-8 encoding. MySQL database, and all tables are in UTF-8 (utf8_general_ci).
At this point everything works fine if I am entering only letters (even international and some weird symbols), but if I enter some of these characters "
, &
, <
or >
, I run into some serious problems...
When I enter such text, everything looks fine in my database, but when I try to create an array for jQuery, it creates an error because of quotes (I suppose that even single quotes are problem here)... So I suppose I should escape them somehow, right? Then I use PHP's htmlspecialchars
and jQuery's array is created correctly. Even when I click inside input field and start typing text, autocomplete shows all those characters correctly. But if I actually select one of the records with those characters, they suddenly appear like html's escaped characters ("
, &
, <
, >
). So I tried to apply htmlspecialchars_decode
to that same input field but it didn't help... Is there a way to display those characters correctly in my input field when I select a record from jQuery's autocomplete?
I've tried to google the problem, but I couldn't find anything to solve my problem... Please help!
Thanks in advance!EDIT:
This is the way I am creating an array for jQuery ($tags
is just a simple array):
<?php
$t = implode(", ", $tags);
?>
<script>
$(document).ready(function(){
var data_tags = "<?php echo htmlspecialchars($t); ?>".split(" | ");
$("#input_tags").autocomplete(data_tags, { multiple: true, multipleSeparator: ", " });
});
</script>
I know it is maybe not the best way, but generally it works :)
I am generating an input field this way:
<?php
function inputField($label, $name, $type, $size, $default=NULL, $misc=NU开发者_运维知识库LL){
$printInput = "<tr><td align=\"right\" valign=\"top\">\n";
$printInput .= $label;
$printInput .= "</td><td>\n";
$printInput .= "<input type=\"".$type."\" size=\"".$size."\" name=\"".$name."\" id=\"".$name."\" value=\"".$default."\"> ".$misc."\n";
$printInput .= "</td></tr>\n";
return $printInput;
}
echo inputField("TAGS", "input_tags", "text", 70, $db_tags);
?>
Try json_encode()
, which requires PHP 5.2.0 or greater.
EDIT You don't need the quotes around a json_encoded value:
var data_tags = <?php echo json_encode($t); ?>;
Try using htmlentities();
instead.
精彩评论