简体   繁体   中英

php cannot read uft8 json

I am now writing Android apps and the apps will use json(utf8):

http://.....xxx.php?json=%7B%22name%22%3A%22peterchan%22%2C%22phone%22%3A%2212345678%22%2C%22password%22%3A%226kxhSJM6iLB0kZ9LZGCEUQ%3S%3D%0A%22%7D

the xxx.php is like:

<?php
    header("Content-Type:text/html; charset=utf-8");
    ini_set('default_charset', 'utf-8');
    $json = $_GET["json"];
    $obj = json_decode($json);
    $name = $obj -> {"name"};
    $phone = $obj -> {"phone"};
    $password = $obj -> {"password"};
    printf($json);
?>

but it returns: Warning: printf() : Too few arguments in xxx.php

Can anyone help me? Please

You should validate json_decode doesn't return null and check for errors if so using json_last_error_msg

Your password ends with a newline (maybe it shouldn't be there), which is percent-encoded as %0A which is invalid because in JSON newlines must be escaped as \\n which would be percent-encoded as %5Cn

demo: https://3v4l.org/vTM2r

$broke = '%7B%22name%22%3A%22peterchan%22%2C%22phone%22%3A%2212345678%22%2C%22password%22%3A%226kxhSJM6iLB0kZ9LZGCEUQ%3S%3D%0A%22%7D';
$fixed = '%7B%22name%22%3A%22peterchan%22%2C%22phone%22%3A%2212345678%22%2C%22password%22%3A%226kxhSJM6iLB0kZ9LZGCEUQ%3S%3D%5Cn%22%7D';

var_dump(urldecode($broke));
// string(80) "{"name":"peterchan","phone":"12345678","password":"6kxhSJM6iLB0kZ9LZGCEUQ%3S=
// "}"

var_dump(json_decode(urldecode($broke)));
// NULL

var_dump(urldecode($fixed));
// string(81) "{"name":"peterchan","phone":"12345678","password":"6kxhSJM6iLB0kZ9LZGCEUQ%3S=\n"}"

var_dump(json_decode(urldecode($fixed)));
// object(stdClass)#1 (3) {
//   ["name"]=>
//   string(9) "peterchan"
//   ["phone"]=>
//   string(8) "12345678"
//   ["password"]=>
//   string(27) "6kxhSJM6iLB0kZ9LZGCEUQ%3S=
// "
// }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM