我需要有关将 python 代码翻译为 PHP 的帮助。脚本就是这样设置的,以便与 API 服务器通信,在这部分代码中使用 POST 登录。
Python 代码已经过测试并且可以工作,但是我无法确定应该以哪种方式将其准确地转换为 PHP,因为我从 API 得到了空响应,这意味着 - 错误。我怀疑使用了错误的 post 参数或 post 方法。在 python 代码中,有一条注释说明了成功 API 返回应该是什么样子。
编辑:
var_dump($结果);返回 bool(false) 并且启用错误报告后,会弹出此警告:
警告:file_get_contents(https://kodi.titlvi.com/api/subtitles/gettoken):无法打开流:HTTP请求失败! HTTP/1.1 404 Not Found in /var/www/html/test.php on line 19 bool(false)
PHP - 当前脚本
<?php
error_reporting(-1);
ini_set('display_errors', 1);
$api_url = "https://kodi.titlovi.com/api/subtitles";
$username = "censored";
$password = "censored";
// sending user login request
$parameters = array('username' => $username, 'password' => $password, 'json' => true);
$options = array('http' => array(
'header' => 'Content-Type: application/x-www-form-urlencoded\r\n',
'method' => 'POST',
'content' => http_build_query($parameters)
));
$context = stream_context_create($options);
$result = file_get_contents($api_url.'/gettoken', false, $context);
var_dump($result);
?>
Python(工作示例)
api_url = 'https://kodi.titlovi.com/api/subtitles'
def handle_login(self):
"""
Method used for sending user login request.
OK return:
{
"ExpirationDate": datetime string (format: '%Y-%m-%dT%H:%M:%S.%f'),
"Token": string,
"UserId": integer,
"UserName": string
}
Error return: None
"""
logger('starting user login')
login_params = dict(username=self.username, password=self.password, json=True)
try:
response = requests.post('{0}/gettoken'.format(api_url), params=login_params)
logger('Response status: {0}'.format(response.status_code))
if response.status_code == requests.codes.ok:
resp_json = response.json()
logger('login response data: {0}'.format(resp_json))
return resp_json
elif response.status_code == requests.codes.unauthorized:
show_notification(get_string(32006))
return None
else:
return None
except Exception as e:
logger(e)
return None Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
param=dictionary将参数放入 URL 查询参数中,而不是 POST 数据中。服务器需要
Content-length:标头,PHP 默认情况下不发送该标头。为了在标头中包含
\r\n,您必须使用双引号,而不是单引号。$username, 'password' => $password, 'json' => True); $options = array('http' => array( 'header' => "Content-Length: 0\r\n", 'method' => 'POST', )); $context = stream_context_create($options); $result = file_get_contents($api_url.'/gettoken?' . http_build_query($parameters), false, $context); var_dump($result); ?>