【问题标题】:Guzzle HTTP, can't parse response to JSONGuzzle HTTP,无法解析对 JSON 的响应
【发布时间】:2018-03-20 20:21:04
【问题描述】:

所以我正在集成来自 3rd 方公司的 API,我正面临这种奇怪的情况。

我使用以下代码获取端点

$client = $this->client = new Client([
    'base_uri' => 'https://xxx.xxxxxxxxxx.com/api/',
    'timeout' => 15
]);

$this->requestConfig = [
    'auth' => [
        'xxxx@xx.xxx',
        'xxxxx'
    ],
    'headers' => [
        'cache-control' => 'no-cache',
        'content-type' => 'application/x-www-form-urlencoded'
    ],

];

$response = $this->client->get($url, $this->requestConfig);

$content = $response->getBody()->getContents();

现在有趣的是,如果我得到 var_dump 内容:

string(66) ""[{\"ExternalId\":\"38\",\"AgencyReference\":\"45436070356676\"}]""

现在我知道这个响应很糟糕,响应类型如果没有设置 json,json 是 URL 编码的,而且一切都不好闻。

我一直在尝试解析这个字符串。

urldecode 也不行。

问题很简单,给出这样的响应,我怎样才能得到一个正常的数组?

目前使用 PHP 7.1

【问题讨论】:

  • 语法错误。谢谢
  • 不,我的意思是使用 json_last_error 调试您的解码错误 :)
  • 看起来你需要在json_decode-ing 之前去掉斜线。如果你这样做$content = json_decode(stripslashes($response->getBody()->getContents()));会发生什么?
  • 感谢 N.B,比 preg_replace 更好

标签: php guzzle6


【解决方案1】:

所以终于找到了这个: Remove backslash \ from string using preg replace of php

解决我的问题。

在这种情况下,转义引号导致 json 格式错误。我的最终代码如下所示。

$response = $response->getBody()->getContents();
$clean = stripslashes($response);
$clean = substr($clean, 1, -1);

dd(json_decode($clean));

请不要这样写你的 API...

只是看起来很糟糕

【讨论】:

    【解决方案2】:

    顺便说一句,Content-Type 在您发送(请求或响应)某些内容时是有意义的。但是你发送了一个没有内容的 GET 请求。

    要指定响应的首选内容类型,您应该使用Accept HTTP 标头,例如Accept: application/json

    我不确定这会解决你的问题,但只是让事情变得清晰和正确;)

    【讨论】:

      猜你喜欢
      • 2013-09-26
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-19
      • 2018-06-29
      相关资源
      最近更新 更多