【问题标题】:php json_decode hang, unable to decode string from POSTphp json_decode 挂起,无法从 POST 解码字符串
【发布时间】:2018-01-23 03:53:33
【问题描述】:

我是 PHP、JSON、js 的新手。

我有一个将 JSON 字符串发送到 PHP 的 js 程序 在 PHP 中使用 json_decode fn 时遇到一些问题。
我尝试将从JS接收的字符串保存到一个文件中,并且json字符串是正确的,没有任何问题。 但是当我尝试使用 json_decode 时,函数挂起(我认为,因为函数调用下面的任何东西都没有被调用,所以我所有的 echo/print 都没有给出任何东西。

下面是我的js代码:

function post()
{
  var test1 = {
    name:"marzzuq",
    age:16
  };
  myjson = JSON.stringify(test1);
  var xmlhttp = new XMLHttpRequest();
  xmlhttp.open("POST","post.php",true);
  xmlhttp.setRequestHeader("Content-type","application/json");
  xmlhttp.send(myjson);
  console.log("\nsend ok: " + myjson);
}

下面是我的php脚本:

<?php
 $rawdata = file_get_contents('php://input');
 file_put_contents('/tmp/test.json', $rawdata);
 $jsson = json_decode($rawdata);
 file_put_contents('/tmp/test3.json', $jsson);
 `echo test >> /tmp/test.txt`;
 ?>

我尝试过使用 htmlentities 和 html_entity_decode:
$result= htmlentities((string)$rawdata);
$result2 = html_entity_decode((string)$rawdata);

并在json_decode 上使用结果,但它不起作用。
fr $rawdata 的长度是 27(使用 strlen),这是正确的。

我尝试打印 json_last_error,但就像我说的那样,json_decode 行下方的所有代码都停止工作,所以什么都不会打印。

switch (json_last_error()) {
    case JSON_ERROR_NONE:
        `echo ' - No errors' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_DEPTH:
        `echo ' - Maximum stack depth exceeded' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_STATE_MISMATCH:
        `echo ' - Underflow or the modes mismatch' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_CTRL_CHAR:
        `echo ' - Unexpected control character found' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_SYNTAX:
        `echo ' - Syntax error, malformed JSON' >> /tmp/test.txt`;
    break;
    case JSON_ERROR_UTF8:
        `echo ' - Malformed UTF-8 characters, possibly incorrectly encoded' >> /tmp/test.txt`;
    break;
    default:
        `echo ' - Unknown error' >> /tmp/test.txt`;
    break;
}

谁能帮帮我?

【问题讨论】:

  • @marekful:我明白了。但即使我删除了该行,json_decode 以下的任何内容仍然无法正常工作。我试过打印这样的东西:echo yes sucess &gt;&gt; /tmp/test.txt;在 json_decode 之后,但它不打印
  • 我已经在这里给你一个详细的例子来说明如何做到这一点:stackoverflow.com/questions/48374719/… 但你忽略了它。
  • @billynoah 我试过你的方法,但也许我做错了什么,因为它不起作用。我会再试一次。谢谢。顺便说一句,您是否删除了您对另一个问题的评论?

标签: javascript php json


【解决方案1】:

这就是我在 PHP 中解码 JSON 的方式。这也是一个 MySQL 插入。我想您可能想对刚刚在 PHP 中收到的数据做一些事情。

首先,我已经序列化的表单数据。

来自 html 表单的键值对序列化数组。

var data = [
{
"name":"CLIENT_ID",
"value":"111"
},
{
"name":"PROJECT_ID",
"value":"222"
},
{
"name":"USER_ID",
"value":"465605"
},
{
"name":"UTL_LATITUDE",
"value":"40.6110589"
},
{
"name":"UTL_LONGITUDE",
"value":"-111.8999353"
},
{
"name":"UTL_EVENT",
"value":"CLOCK IN"
},
{
"name":"UTL_ACTION",
"value":"MEETING"
}
];

将其字符串化以提交给 PHP...

php_decode 函数需要这种格式的 JSON。

[{"name":"CLIENT_ID","value":"111"},{"name":"PROJECT_ID","value":"222"},{"name":"USER_ID","value":"465605"},{"name":"UTL_LATITUDE","value":"40.6110589"},{"name":"UTL_LONGITUDE","value":"-111.8999353"},{"name":"UTL_EVENT","value":"CLOCK IN"},{"name":"UTL_ACTION","value":"TRAVEL"}]

.

<?php
/* Status Codes

return 0 = Nothing to Update (n/a)
return 1 = Successful Insert Query
return 2 = Database Connection refused
return 3 = MySQL Query Error OR Wrong URL Parameters */

/* Disable Warnings so that we can return ONLY what we want through echo. */
mysqli_report(MYSQLI_REPORT_STRICT);

// First get raw POST input
$raw_post     = file_get_contents('php://input');
// Run through url_decode..
$url_decoded  = urldecode($raw_post);
// Run through json_decode...
$json_decoded = json_decode($url_decoded, false); // false to allow for reference to oject. eg. $column->name instead of $column["name"] in the foreach.

$client_id      = (strlen($json_decoded[0]->value) > 0 ? $json_decoded[0]->value : null);
$project_id     = (strlen($json_decoded[1]->value) > 0 ? $json_decoded[1]->value : null);
$user_id        = (strlen($json_decoded[2]->value) > 0 ? $json_decoded[2]->value : null);
$utl_latitude   = (strlen($json_decoded[3]->value) > 0 ? $json_decoded[3]->value : null);
$utl_longitude  = (strlen($json_decoded[4]->value) > 0 ? $json_decoded[4]->value : null);
$utl_event      = (strlen($json_decoded[5]->value) > 0 ? $json_decoded[5]->value : null);
$utl_action     = (strlen($json_decoded[6]->value) > 0 ? $json_decoded[6]->value : null);

// INCLUDE DB CONNECTION STRING
//include 'php_pdo_mysql_connect.php';

mysqli_report(MYSQLI_REPORT_STRICT);

$host = 'localhost';
$db   = 'alpha1';
$user = 'root';
$pass = 'password';
$charset = 'utf8mb4';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES   => false,
];

try {

$link = new PDO( $dsn, $user, $pass, $opt ); 

return $link;

} catch( PDOException $e) {

// Any error at this point...
$originalError = $e->getCode();

// MySQL Database connection refused..
if ($originalError == '2002') {

// Custom error.
echo '2';
exit;

}

}

// SQL INSERT query...
$stmt = $link->prepare("

INSERT INTO tbl_user_time_log 

( 
    CLIENT_ID, 
    PROJECT_ID,
    USER_ID,
    UTL_LATITUDE,
    UTL_LONGITUDE,
    UTL_EVENT,
    UTL_ACTION
)

VALUES 

( 

:client_id,
:project_id,
:user_id,
:utl_latitude,
:utl_longitude,
:utl_event,
:utl_action

) 

");

// Bind the corresponding parameter.
$stmt->bindParam(':client_id', $client_id, PDO::PARAM_INT);         // INT
$stmt->bindParam(':project_id', $project_id, PDO::PARAM_INT);       // INT
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);             // STR

$stmt->bindParam(':utl_latitude', $utl_latitude, PDO::PARAM_STR);   // STR
$stmt->bindParam(':utl_longitude', $utl_longitude, PDO::PARAM_STR); // STR



$stmt->bindParam(':utl_event', $utl_event, PDO::PARAM_STR);         // STR
$stmt->bindParam(':utl_action', $utl_action, PDO::PARAM_STR);       // STR

// Execute this SQL statement.
$stmt->execute(); 

// Catch pk generated for this new record. 
// $pk_user_time_log_id = $link->lastInsertId();

$link = null;
$stmt = null;

// return 1 = Successful Insert Query
echo '1';

?>

【讨论】:

  • 我一开始有相同的代码,但是代码停在json_decode(我认为)
  • 查看数组格式的更新答案。键值对。
  • 在 js 脚本中,我已经对其进行了字符串化,就像我在问题中所做的那样。 json_decode 将起作用,如果我使用从 POST 收到的相同字符串但不使用 file_get_contents('php://input'); 但是当我直接使用来自 file_get_contents 的输入时,它会失败
【解决方案2】:

其实主要问题是 html 字符,你可以使用 html_entity_decode() 函数将所有实体转换为适用的字符!

json_decode(html_entity_decode('your variable here'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 2014-01-02
    • 2011-02-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    相关资源
    最近更新 更多