PHP Base64 encoding for JSON slash issue PHP Base64 encoding for JSON slash issue elasticsearch elasticsearch

PHP Base64 encoding for JSON slash issue


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("[\n\r]", "")}"

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);


Please use php function

addslashes() to add slash or any special character , to retrive slashes use stripslashes().

thanks...