繁体   English   中英

php json_decode挂起,无法从POST解码字符串

[英]php json_decode hang, unable to decode string from POST

我是PHP,JSON,js的新手。

我有一个js程序,它将JSON字符串发送到PHP。在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行下面的所有代码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;
}

谁能帮我?

这就是我在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';

?>

实际上,主要的问题是html字符,您可以只使用html_entity_decode()函数将所有实体转换为它们的适用字符!

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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