Guzzle和无法解析对JSON的响应

时间:2013-09-20 14:56:39

标签: php xml json guzzle

我用这个方法有一个小的php api客户端:

private function send($endpoint)
{
    $headers = array();
    $body = $this->xmlSerialiser->convertToXML($this->getQueue());

    try {
        $response = json_decode(
            $this->guzzleClient->post(
                $endpoint,
                $headers, $body
            )
            ->send()
            ->json()
        );

    } catch (\Guzzle\Http\Exception\BadResponseException $e) {
        $response = array('Error' => $e->getMessage());
    }

    return $response;
}

我一直在接受

Unable to parse response body into JSON: 4 (500 Internal Server Error)

我已经尝试了解服务器响应的示例,似乎没问题:

echo (string) $this->guzzleClient->post(
                $endpoint,
                $headers, $body
            )
            ->send()->getBody();

这就是结果:

<Messages xmlns="http://www.example.com/xxx/3.0">

<GetAccountResponse RequestType="GetAccount">

    <AccountId>xxxx-xxx-xxx-xxxx-xxxx</AccountId>

    <Token>xxxxxxxxxxxxxx/t3VkEJXC7f6b6G4yPJSZ5QfT2hdSQXUmi0e8cndSYLK4N7mswRHifzwGHLUJYHM17iGL8s=</Token>

</GetAccountResponse>

2 个答案:

答案 0 :(得分:1)

我自己回答了

Guzzle文档说:json方法 - &gt;解析JSON响应主体并返回一个数组

所以在我的情况下,我需要将json mehod切换为xml(因为响应是xml)。

最后这是结果:

private function send($endpoint)
{
    $headers = array();
    $body = $this->xmlSerialiser->convertToXML($this->getQueue());

    try {
        $response = (array)(
            $this->guzzleClient->post(
                $endpoint,
                $headers, $body
            )
            ->send()
            ->xml()
        );
    } catch (\Guzzle\Http\Exception\BadResponseException $e) {
        $response = array('Error' => $e->getMessage());
    }

    return $response;
}

答案 1 :(得分:1)

使用以下代码。

 $response->getBody()->getContents() 
相关问题