簡體   English   中英

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

[英]PHP header('Content-Type: application/json'); is not working

對不起,如果它是重復的問題,已經嘗試了谷歌和 StackOverflow 中的每一個建議。

出於某種原因,我的響應標頭總是以 Content-Type:text/html; 的形式出現。 字符集=UTF-8。

我希望內容類型為 json (Content-Type:application/json),不知道我做錯了什么。 這是我的代碼

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

回復:

在此處輸入圖像描述

我有同樣的問題。 發生這種情況是因為在一個 php 文件中我有幾個

部分。
 ======== File.php ========= <?php //some code ?> <?php //some other code ?> ===========================

我已經通過僅在一個標簽中合並代碼來修復它。

以這種方式測試: ContentType : "application/x-www-form-urlencoded"

請檢查此行之前是否有警告:

header('Content-Type: application/json;charset=utf-8');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM