请求失败时如何在电报机器人中检索 sendmessage 的结果 [in php]?

How to retrieve result of sendmessage in telegram bot while the request is fails [in php]?

我通过 php 以这种方式向电报机器人发送请求:

<?php
$res=file_get_contents($request);
echo($res);

当您发送有效的 $request 时,我会收到一条反馈($res),内容为:

{"ok":true,"result":{"message_id":***,"from":{"id":***,"is_bot":true,"first_name":"**","username":"*****"},"chat":{"id":*****,"first_name":"***","username":"***","type":"private"},"date":1505286416,"text":"test"}}

但是当 $request 中出现问题时,我希望从 $res 收到类似这样的信息:

{"ok":false,"error_code":400,"description":"Bad Request: chat not found"}

相反,我收到警告并且 $res 为 NULL:

Warning: file_get_contents(*******): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in /home/test/public_html/test.php on line 2

我应该如何访问 $res 中的电报响应?

如果您需要获得错误响应,则不能使用 file_get_contents,请尝试使用 cURL。

$url = "https://api.telegram.org/botTOKEN/getChat?chat_id=-1";

$curl = curl_init();
curl_setopt_array($curl, [
    CURLOPT_URL => $url,
    CURLOPT_RETURNTRANSFER => true
]);
$data = curl_exec($curl);
curl_close($curl);

$result = json_decode($data, true);