dtcd27183 2016-02-06 10:14
浏览 393
已采纳

用于JSON斜杠问题的PHP Base64编码

I am using 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.

However, PHP's Base64 generates slashes \ in the encoded string. The JSON which I am trying to construct with this encoding, cannot be parsed by Elastic:

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

I do not want to remove/replace the slashes, as suggested in some Stackoverflow posts, since it may cause problems later with decoding.

How are slashes in Base64 encoding dealt with in such scenarios?

  • 写回答

2条回答 默认 最新

  • dtjpnd7517 2016-02-06 10:47
    关注

    It is better not to build the JSON string yourself, but to let json_encode do the job, which takes care of slashes. You don't need addslashes then:

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

    Note that the new line characters that you insert with chunk_split will be escaped during the encoding, as JSON does not allow non-escaped line breaks in strings. If the receiving end decodes the JSON string in the right way, it will result in the value $obj has in the above code, with content having line breaks.

    In an Elastic blog post, the author even removes any line breaks in the base64 encoded string. The Scala code presented there has this:

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

    This really seems to suggest you shouldn't be using chunk_split either, so then the suggested PHP code becomes:

    // create the object
    $obj = array(
        "content" => base64_encode($file_contents)
    );
    // encode the object in JSON format
    $json = json_encode($obj);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划