【问题标题】:PHP Base64 encoding for JSON slash issueJSON斜线问题的PHP Base64编码
【发布时间】:2016-05-16 08:31:04
【问题描述】:

我正在使用Elastic-PHP API 2.0 创建 Word 和 PDF 文档的索引。这通常需要将文档的 Base64 编码作为 JSON 发送到其Mapper attachment plugin

但是,PHP 的 Base64 会在编码字符串中生成斜线 \。我试图用这种编码构造的 JSON 不能被 Elastic 解析:

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

我不想像suggested in some Stackoverflow posts 那样删除/替换斜线,因为它可能会导致以后解码出现问题。

在这种情况下如何处理 Base64 编码中的斜线?

【问题讨论】:

    标签: php json elasticsearch base64


    【解决方案1】:

    最好不要自己构建 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);
    

    【讨论】:

      【解决方案2】:

      请使用php函数

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

      谢谢...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-12
        • 2015-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多