【发布时间】:2021-10-11 20:50:22
【问题描述】:
我正在尝试为 WHMCS 创建一个模块。它接受以下格式:
{"verifyConn": 1}
但是我的 API 返回:
{
"verifyConn":1
}
由于某种原因,它无法使用第二种格式。所以我想把所有的空白都去掉,转换成上面的格式。
知道我该怎么做吗?
我的代码总结:
class Response {
private $_verifyConn;
// define private variables
// define verifyConn method - numeric status code
public function verifyConn($verifyConn) {
$this->_verifyConn = $verifyConn;
}
// define the send method - this will send the built response object to the browser
// in json format
public function send() {
// set response header contact type to json utf-8
header('Content-type:application/json;charset=utf-8');
// set statusCode in json response
$this->_responseData['verifyConn'] = $this->_verifyConn;
// encode the responseData array to json response output
echo json_encode($this->_responseData);
}
}
$response = new Response();
$response->verifyConn(1);
$response->send();
【问题讨论】:
-
空格在 JSON 中应该无关紧要。请参阅:Are whitespace characters insignificant in JSON? 您的问题可能是其他问题。您是否生成了 JSON?如何?有代码吗?
-
当我在 strong 中回显 "{"verifyConn": 1}" 以测试 WHMCS 返回成功,但是当我以带有空格的 JSON 格式回显时它不能成功。我已添加到我使用过的代码的原始帖子摘要中
-
感谢您的代码。
json_encode()通常会在没有额外空格的情况下进行编码。您必须使用JSON_PRETTY_PRINT标志来获得额外的空白。见:json_encode() in the manual -
谢谢!你让我意识到我在 Postman 上使用 Pretty view 实际上这段代码返回时没有任何空格问题是我在 WHMCS 端使用的凭据。
-
好的,很高兴你找到了问题。