PHP需要输出'而不是'

时间:2014-06-19 10:33:00

标签: javascript php apostrophe

我遇到了jbar的问题,它正在输出'并导致javascript中断。我的代码是:

<div class="jbar" data-init="jbar" data-jbar='{
"message" : "<?php echo $myann->getValue("heading", 0); ?>",
"button"  : "<?php echo $myann->getValue("buttonText", 0); ?>",
"url"     : "<?php echo $myann->getValue("buttonURL", 0); ?>",
"state"   : "open"
}'></div>

如果我手动输入:

"message" : "My name's test",

这打破了。如果我输入:

"message" : "My name&#39;s test",

这有效!

那么......我怎样才能让php echo使用'而不是'?我已经尝试过htmlspecialchars和addslashes,但都没有工作。

感谢。

2 个答案:

答案 0 :(得分:1)

来自documentation

  

“'”(单引号)仅在设置ENT_QUOTES时变为'''(或')。

所以

echo htmlspecialchars($input, ENT_QUOTES);

答案 1 :(得分:1)

使用json_encode()

<?php
$arr = array(
    "message" => $myann->getValue("heading", 0),
    "button"  => $myann->getValue("buttonText", 0),
    "url"     => $myann->getValue("buttonURL", 0),
    "state"   => "open",
);
?>
<div class="jbar"
     data-init="jbar"
     data-jbar='<?php echo json_encode($arr); ?>'></div>
相关问题