PHP JSON 斜杠问题的 Base64 编码

PHP Base64 encoding for JSON slash issue

我正在使用 Elastic-PHP API 2.0 to create an index of Word and PDF documents. This normally requires to send a Base64 encoding of the document as JSON to its Mapper attachment plugin

然而,PHP 的 Base64 在编码字符串中生成斜杠 \。我试图用这种编码构造的 JSON 无法被 Elastic 解析:

$json = 
    '{"content" : "'.addslashes(chunk_split(base64_encode($file_contents))).'"}'

我不想 remove/replace 斜线,如 ,因为它可能会导致以后的解码问题。

这种场景下Base64编码中的斜杠是怎么处理的?

最好不要自己构建 JSON 字符串,而让 json_encode 来完成这项工作,这会处理斜杠。您不需要 addslashes 然后:

// create the object
$obj = array(
    "content" => chunk_split(base64_encode($file_contents))
);
// encode the object in JSON format
$json = json_encode($obj);

请注意,您使用 chunk_split 插入的新行字符将在编码期间被转义,因为 JSON 不允许非转义行断弦。如果接收端以正确的方式解码JSON字符串,将得到上面代码中$obj的值,其中content 有换行符。

Elastic blog post 中,作者甚至删除了 base64 编码字符串中的任何换行符。那里提供的 Scala 代码是这样的:

"image" :"${new BASE64Encoder().encode(data).replaceAll("[\n\r]", "")}"

这似乎真的建议您也不应该使用 chunk_split,因此建议的 PHP 代码变为:

// create the object
$obj = array(
    "content" => base64_encode($file_contents)
);
// encode the object in JSON format
$json = json_encode($obj);

请使用php函数

addslashes() 添加斜杠或任何特殊字符,使用 stripslashes() 检索斜杠。

谢谢...