1

I'm writing a client for an API...

use Zend\Http\Client;
use Zend\Http\Request;
use Zend\Json\Json;
...
$request = new Request();
$request->getHeaders()->addHeaders([
    'Accept-Charset' => 'UTF-8',
    'Accept' => 'application/hal+json',
    'Content-Type' => 'application/hal+json; charset=UTF-8',
]);
$apiAddress = 'http://my.project.tld/categories';
$request->setUri($apiAddress);
$request->setMethod('GET');
$client = new Client();
$response = $client->dispatch($request);
$data = $response->getContent();

... and get a broken JSON like this:

1f9e <-- What is it?
{"_links...
\u043 <-- What is it?
1a6...
tfoli <-- What is it?
0

The string is separaten into five lines:

  • 1st line: only 1f9e
  • 2nd line: first content part
  • 3d line: string 1a6
  • 4th line: the second content part
  • 5th line: 0

Why am I getting additional symbols/strings? How to avoid this a get valid JSON output?

automatix
  • 14,018
  • 26
  • 105
  • 230

1 Answers1

4

The problem with the getContent() method of the response object. It may not decode the content it gets in it from the request. Please have a look at here. This might be the reason. I may be wrong!

So the getBody() method of it does the decoding job for the content of the request. So please use this method instead of getContent().

$data = $response->getBody();

Hope this would help you!

unclexo
  • 3,691
  • 2
  • 18
  • 26
  • Thank you very much for your answer! I didn't use the `getBody()` because I trusted in the autocomplete function of my IDE. The `Zend\Http\Client#dispatch(...)` returns a `Zend\Stdlib\ResponseInterface`. I didn't consider it and, when I so only `getContent(...)` and `getMetadata(...)`, I thought, that the `getBody(...)` were not provided anymore. But sure, the concrete object returned by the `dispatch(...)` is a `Zend\Http\Response` and it provides the method I need -- `getBody()`. Now it's working. Thanks a lot! – automatix Jul 07 '17 at 23:06