dsdzz04802 2017-10-05 20:55
浏览 549

PHP标题('Content-Type:application / json'); 不管用

Sorry if it is repeated question, already tried every single suggestion in google and StackOverflow.

For some reason, my response header always comes as Content-Type:text/html; charset=UTF-8.

I want content type to be json (Content-Type:application/json), Not sure what am I doing wrong. here is my code

    <?php
    header('Access-Control-Allow-Origin: *');

    define('__ROOT__', dirname(dirname(__FILE__)));
    require_once(__ROOT__.'/api/csvtojson.php');
    require_once(__ROOT__.'/api/retrieve-login-data.php');
    require_once(__ROOT__.'/api/access-control.php');
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);

    //Make sure that it is a POST request.
    if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
        throw new Exception('Request method must be POST!');
    }

    //Make sure that the content type of the POST request has been set to application/json
    $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
    if(strcasecmp($contentType, 'application/json') != 0){
        throw new Exception('Content type must be: application/json');
    }

    //Receive the RAW post data.
    $content = trim(file_get_contents("php://input"));

    //Attempt to decode the incoming RAW post data from JSON.
    $decoded = json_decode($content, true);

    //If json_decode failed, the JSON is invalid.
    if(!is_array($decoded)){
        throw new Exception('Received content contained invalid JSON!');
    }
$filename =     $decoded['filename'];

   // open csv file
    if (!($fp = fopen($filename, 'r'))) {
      die("Can't open file...");
      }
    //read csv headers
    $key = fgetcsv($fp,"1024",",");
    // parse csv rows into array
    $json = array();
    while ($row = fgetcsv($fp,"1024",",")) {
      $json[] = array_combine($key, $row);
      }
    // release file handle
    fclose($fp);
    // encode array to json
    header('Content-Type: application/json;charset=utf-8');
    echo (json_encode($json, JSON_PRETTY_PRINT));

Response:

enter image description here

  • 写回答

2条回答 默认 最新

  • drap5081683 2017-10-05 20:57
    关注

    test this way : ContentType : "application/x-www-form-urlencoded"

    评论

报告相同问题?

悬赏问题

  • ¥15 VS2022 C++的相关代码问题咨询
  • ¥15 如果要做一个老年人平板有哪些需求
  • ¥15 k8s生产配置推荐配置及部署方案
  • ¥15 matlab提取运动物体的坐标
  • ¥15 人大金仓下载,有人知道怎么解决吗
  • ¥15 一个小问题,本人刚入门,哪位可以help
  • ¥30 python安卓开发
  • ¥15 使用R语言GD包一直不出结果
  • ¥15 计算机微处理器与接口技术相关问题,求解答图片的这个问题,有多少个端口,端口地址和解答问题的方法和思路,不要AI作答
  • ¥15 如何根据一个截图编写对应的HTML代码