发出添加Content-Length作为标头PHP JSON的问题

时间:2019-05-31 17:02:38

标签: php json http

我试图添加内容长度以在POSTMAN中正确显示,但是由于某种原因,即使存在JSON响应,我也仍然收到关于Content-Length的空响应。

以下是我用来创建JSON的PHP脚本: 我尝试将变量集设置为strlen($jsoncount);,但没有任何运气。

<?php

header("Content-Type: application/json; charset=UTF-8");
header("Content-Length: ".filesize($length));

$con=mysqli_connect("localhost","username","password","database");

// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// This SQL statement selects ALL from the table 'Equipment'


$username = $_POST['username'];
$password = $_POST['password'];



$sql = "SELECT id, name, username FROM TABLE1 WHERE (username = '$username') and password = '$password' ";

// Check if there are results
if ($result = mysqli_query($con, $sql))
{
    // Create temporary connection
    $resultArray = array();
    $tempArray = array();

    // Look through each row
    $row = $result->fetch_object();
    if ($row) {

       echo json_encode($row, JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK);
       $jsoncount = (json_encode($row, JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK));
        $length = strlen($jsoncount);
       //echo fetch_object(); 
    } else {
    echo '';
    }   $row = $result->fetch_object();


    // Finally, encode the array to JSON and output the results
    //echo json_encode($resultArray);

}

mysqli_close($con);


?>

1 个答案:

答案 0 :(得分:0)

您需要确保您具有JSON内容,并且可以在设置标题之前获取长度。因此,请从页面顶部删除标题,并将末尾的代码更改为...

if ($row) {
   $jsoncount = json_encode($row, JSON_PRETTY_PRINT | JSON_NUMERIC_CHECK);
   $length = strlen($jsoncount);
   header("Content-Type: application/json; charset=UTF-8");
   header("Content-Length: ".$length);
   echo $jsoncount; 
} else {