Emre Emre - 1 month ago 5x
PHP Question

Php base64 and ruby are not the same result

I am trying to convert my php code into ruby by using Base64 but they do not give the same results;

PHP code;

$user_basket = base64_encode( json_encode( array(array("My basket", "18.00", 2))));

echo $user_basket;

which outputs;


Then I try the same thing in ruby;

user_basket = Base64.encode64((([["My basket", "18.00", 2]]).to_json).gsub!(/\"/, '\''))

I put gsub because
adds backslashes.

this outputs;



The problem is with the to_json conversation;
In php the output is;

json_encode( array(array("My basket", "18.00", 2)))
>> [["My basket","18.00",2]]

In ruby;

([["My basket", "18.00", 2]]).to_json
>> "[[\"My basket\",\"18.00\",2]]"

ruby adds backslash that is why I add gsub to remove backslashes.


Neither Ruby's to_json not PHP's json_encode add back slashes to the actual string. However, when printing the string in IRB, backslashes are added in this displayed representation to be a valud string. They are not in the actual string data however.

In contrast what @Neat said in his comment, Ruby also doesn't add single-quites in its JSON output. With your original code however, the would be present since you are replacing all literal double-quote characters with a single quote character with your gsub!.

The confusion probably stems from you forgetting the actual json_encode call in your PHP version. When running the actual code, both versions produce the exact same string:

PHP> json_encode( array(array("My basket", "18.00", 2)));
# => "[[\"My basket\",\"18.00\",2]]"

RUBY> [["My basket", "18.00", 2]].to_json
# => "[[\"My basket\",\"18.00\",2]]"

When encoding the string as base64, the result is thus also the same:

PHP> base64_encode( json_encode( array(array("My basket", "18.00", 2))));
# => "W1siTXkgYmFza2V0IiwiMTguMDAiLDJdXQ=="

RUBY> Base64.strict_encode64 [["My basket", "18.00", 2]].to_json
# => "W1siTXkgYmFza2V0IiwiMTguMDAiLDJdXQ=="