php无法读取uft8 json

时间:2017-07-01 15:45:19

标签: php android json utf-8

我现在正在编写Android应用程序,应用程序将使用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

xxx.php就像:

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

但它返回: Warning: printf()xxx.php

中的参数太少

任何人都可以帮助我吗?请

1 个答案:

答案 0 :(得分:2)

您应该验证json_decode不返回null并使用json_last_error_msg

检查错误。

您的密码以换行符结束(也许它不应该在那里),percent-encoded%0A这是无效的,因为in JSON newlines must be escaped as \n会被百分比编码为%5Cn

演示: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=
// "
// }