Problem using json_decode() and json_encode()

Asked

Viewed 505 times

1

I have these string examples I get as urlencoded POST:

data%5Bst_cartaodetalhes_recb%5D=TID%3A+000000%0ACart%E3o%3A+0000%2A%2A%2A%2A%2A%2A%2A%2A0000%0AAutoriza%E7%E3o%3A+0%0ABandeira%3A+

Another example:

data%5Bst_descricao_cb%5D=Conta+Corrente-+Ita%FA

I want to create an object with this string, but I’m not able to work with the encoding, whenever I try to give a json_encode or json_decode return me a json_last_error() = 4 JSON_ERROR_SYNTAX and the string is empty or a string with only []

The biggest problem is that I can’t touch the json I get because it’s from a third party who sends a hook to process...

Previously I only saved a log of what was coming in the hook this way:

$raw_data = file_get_contents("php://input");
$post = $_POST;

log_hook( "webhook post".PHP_EOL.json_encode($_POST));
log_hook( "webhook raw".PHP_EOL.$raw_data);

Considerations:

log_hook( "webhook raw".PHP_EOL.$raw_data); Always prints what comes in the request, and special characters are printed as the hexadecimal representation: %C1 = Á

log_hook( "webhook post".PHP_EOL.json_encode($_POST)); Only prints json correctly if the request has no special character of the type %C1 = Á

With that I could see that json_encode just did not return me a valid json when the hook possessed some of these characters "strange".

How should I process these Hooks? I tried using variations of urldecode, rawurldecode, utf8_decode[1], utf8_encode[1] and nothing worked.. the most was converting the character to and still not processing json.

[1] Even knowing that the last two have nothing to do with the type of coding.

  • Try applying urldecode to the string and then json_encode

  • Next man tries this: utf8_encode(urldecode($url));

1 answer

2


This way you fix the charset and turn into json.

$urldec = "data%5Bst_cartaodetalhes_recb%5D=TID%3A+000000%0ACart%E3o%3A+0000%2A%2A%2A%2A%2A%2A%2A%2A0000%0AAutoriza%E7%E3o%3A+0%0ABandeira%3A+";

mb_parse_str(utf8_encode(urldecode($urldec)), $result);
$json = json_encode($result);

echo $json;
  • If it works out, let me know.

  • 1

    I don’t know if $result = []; it is necessary, moreover, worked well :)

  • In this case it needs $result as it will transform the string into an array, in which case it needs to be passed to the function. $result is the final result of the array. Strange because you expect it to be , $result = mb_parse_str(utf8_encode(urldecode($urldec)); but php has some functions that use parameter as reference. http://php.net/manual/en/function.mb-parse-str.php

  • 1

    You don’t understand, $result doesn’t need to be initialized on the line above :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.