【问题标题】:PHP JSON convertionPHP JSON 转换
【发布时间】: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 端使用的凭据。
  • 好的,很高兴你找到了问题。

标签: php json regex


【解决方案1】:

对于 JSON,空格并不重要。

可能是什么原因: 将内容类型设置为 json。如果 WHMCS 正在等待 json 字符串,如果您知道已将其编码为 json json_encode($this->_responseData),则没有理由将 json 字符串声明为 json 字符串。 WHMCS 已经在等待它了。只需删除/注释掉:

// set response header contact type to json utf-8

header('Content-type:application/json;charset=utf-8');

试一试,看看你会得到什么回应。

您的浏览器上是否安装了任何 json 漂亮的打印插件? 这可能意味着没有空间,您的浏览器只是将字符串格式化为可读格式

【讨论】:

    猜你喜欢
    • 2012-02-08
    • 2013-10-11
    • 2021-08-05
    • 2012-12-22
    • 1970-01-01
    • 2023-03-27
    • 2016-08-01
    • 2023-03-09
    • 2015-07-02
    相关资源
    最近更新 更多