问题
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?
回答1:
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!
来源:https://stackoverflow.com/questions/44978260/how-get-a-valid-json-output-from-the-response-in-zend-framework-3