PHP未返回application/json响应,Python请求JSON报错如何解决?
问题分析与解决方案
核心问题
返回text/html且触发JSON解码错误,本质是PHP代码执行时产生了错误,输出了HTML格式的错误页面,而非预期的JSON内容。
具体修复步骤
1. 修复PHP代码的变量初始化与参数检查问题
你的PHP代码中$result变量未声明就直接赋值,且未检查请求参数是否存在,在开启错误提示的PHP环境下会触发报错,导致输出HTML错误页面,覆盖了JSON响应。
修改后的PHP代码:
<?php // 初始化空数组,避免未定义变量错误 $result = []; // 检查参数是否存在,防止参数缺失时触发报错 $firstname = isset($_GET["firstname"]) ? htmlspecialchars($_GET["firstname"]) : ''; $lastname = isset($_GET["lastname"]) ? htmlspecialchars($_GET["lastname"]) : ''; $password = isset($_GET["password"]) ? htmlspecialchars($_GET["password"]) : ''; $result['username'] = $firstname; // 清空输出缓冲区,确保header发送前无任何多余输出(比如文件开头的空格、BOM头) ob_clean(); header('Content-Type: application/json; charset=utf-8'); echo json_encode($result); exit ; ?>
2. 确认请求参数传递逻辑(可选调整)
你的Python代码用requests.post()加params参数,本质是把参数拼在URL查询串里(GET方式传递),PHP用$_GET接收是合法的。如果需要改用POST方式传递参数,可调整两边代码:
改为POST参数传递的代码示例
PHP代码(接收POST参数):
<?php $result = []; $firstname = isset($_POST["firstname"]) ? htmlspecialchars($_POST["firstname"]) : ''; $lastname = isset($_POST["lastname"]) ? htmlspecialchars($_POST["lastname"]) : ''; $password = isset($_POST["password"]) ? htmlspecialchars($_POST["password"]) : ''; $result['username'] = $firstname; ob_clean(); header('Content-Type: application/json; charset=utf-8'); echo json_encode($result); exit ; ?>
Python代码(用data传递POST数据):
import requests def send(firstname,lastname,password): userdata = {"firstname": firstname, "lastname":lastname , "password": password} resp = requests.post('http://www.example.com/php.php', data=userdata) print('Content-Type:') print(resp.headers['Content-Type']) # 先打印响应内容,方便排查问题 print('响应内容:', resp.text) getdata = resp.json() print(getdata['username']) send('yama','last','password')
3. 排查服务器端错误
如果修改后仍有问题,可通过以下方式排查:
- 在Python代码中打印
resp.text,查看实际返回的内容(是否是404页面、500错误页面) - 查看PHP服务器的错误日志,定位具体报错信息
测试验证
修改后运行Python代码,若返回Content-Type: application/json; charset=utf-8并正确输出yama,则问题解决。
内容的提问来源于stack exchange,提问作者yam ka
相关产品推荐
相关产品推荐

