在使用wp_remote_post之前对HTML内容进行消毒


Sanitize HTML Content before using wp_remote_post

我有一个WordPress插件,它会收集帖子的信息,如帖子标题、帖子内容,并发送到第三方应用程序进行分析。

基本上将帖子标题和帖子内容存储到数组中,将数组编码为JSON格式,并通过wp_remote_post发送给第三方应用程序。我在帖子内容中面临挑战,可能会包含一些html标签并破坏我的JSON数据。

我应该怎么做才能防止帖子内容破坏我的JSON数据?我应该消毒还是用其他方式?

示例代码如下:

$args = array(
    'title' => get_the_title(),
    'content' => get_the_content()
);
$json = json_encode($args);
wp_remote_post( 'http://dummydomain.com/', array(
    'body' => array(
        'data' => $args
    )
) );

您所需要做的就是将额外的标志传递给json_encode,通知它您的代码可以包含HTML标记。通过这两个标志就足够了:

JSON_HEX_TAG-全部<和>被转换为''u003C和''u003E。自PHP 5.3.0起提供。JSON_HEX_QUOT-All"转换为''u0022。自PHP 5.3.0起提供。

http://php.net/manual/en/json.constants.php

你的代码可能是这样的:

$args = array(
    'title' => get_the_title(),
    'content' => get_the_content()
);
$json = json_encode($args, JSON_HEX_TAG | JSON_HEX_QUOT);
wp_remote_post( 'http://dummydomain.com/', array(
    'body' => array(
        'data' => $json
    )
) );