【问题标题】:Wordpress json_encode and json_decode with quotes, slashes, emojisWordpress json_encode 和 json_decode 带引号、斜线、表情符号
【发布时间】:2020-12-14 20:38:20
【问题描述】:

我有一个数据数组,例如

array(
    'question' => 'Title here',
    'options'  => array( 'Option here', 'Option here' )
)

现在,标题/选项可以包含特殊字符,例如“引号”和“单个字符”,以及可能/斜线或表情符号。

不幸的是,在将这些添加到数据和编码后,我无法对其进行解码。 好吧,相反,WordPress 只是返回空。

$encoded = json_encode( $poll_data );
// save, retrieve from DB
$decoded = json_decode( $retrieved );

以上,$retrieved 是:

{"question":"This is \"some quotes\" and also \'single quotes\'","options":["Here is an emoji: ud83dude06","With some slashes/too and back\\as well"]}

但 $decoded 最终为空/null

我尝试了各种添加/stipslashes 以及 htmlspecialentities 都无济于事

【问题讨论】:

  • 你必须避开你的反斜杠。看看这里:stackoverflow.com/questions/32056940/…
  • 这能回答你的问题吗? How to deal with backslashes in json strings php
  • @kuh-chan 它实际上失败了,只有一个 ' 或双引号,即使没有斜线
  • 如果您转义反斜杠,您的示例看起来不错:3v4l.org/sSn6m(只需反斜杠即可转义反斜杠和反斜杠。所以您需要 4 个而不是 2 个反斜杠:)
  • 解码前有没有试过设置成UTF-8? $var = htmlentities($retrived, ENT_QUOTES, "utf-8" ); $decoded = json_decode( $var );

标签: php json wordpress


【解决方案1】:

所以,这最终成为在 json_encode 之前清理字符串的正确方法

$data = wp_encode_emoji( addslashes( stripslashes( htmlspecialchars ( $poll_question ) ) ) )
json_encode( $data );

看起来很疯狂,但它适用于引号、双引号、斜线和表情符号。

【讨论】:

    猜你喜欢
    • 2018-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-03
    • 2013-12-25
    相关资源
    最近更新 更多