很抱歉,如果是重复的问题,已经尝试了google和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));
响应:
答案 0 :(得分:0)
请检查此行之前是否有警告:
header('Content-Type: application/json;charset=utf-8');
答案 1 :(得分:0)
我有同样的问题。发生这种情况是因为在一个php文件中我有几个
部分。======== File.php =========
<?php
//some code
?>
<?php
//some other code
?>
===========================
我已通过仅将代码合并到一个标签中来解决此问题。
答案 2 :(得分:-1)
以这种方式测试: ContentType:&#34; application / x-www-form-urlencoded&#34;