I'm using Slim php framework with a database that contains complex HTML content, but when calling the get method it returns a bad json. Here's the return code
$response->withJson($resp, 201);
I also tried with json_encode but still not valid:
$response->withJson(json_encode($resp), 201);
I just noticed that the JSON returned is missing '}]' at the end, is it possible that the content is too long to be transferred as a string ? Also when i call var_dump($resp)
it shows my content correctly
If you are missing }]
at then end, then one of your PHP files has two spaces (or new lines) before the opening <?php
.
Another solution is to replace your $app->run()
with:
$response = $app->run(true); //Silent mode, wont send the response
$response = $response->withoutHeader("Content-Length"); //Remove the Content-Length
$app->respond($response); //Now we send the response
Hopefully, we'll have a proper fix in the next version!
Maybe a problem with the characters codification. Have you tried this?
json_encode($array, JSON_UNESCAPED_UNICODE)
Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?
As far as I can tell, Slim does not care doing error checking:
/**
* Json.
*
* Note: This method is not part of the PSR-7 standard.
*
* This method prepares the response object to return an HTTP Json
* response to the client.
*
* @param mixed $data The data
* @param int $status The HTTP status code.
* @param int $encodingOptions Json encoding options
* @return self
*/
public function withJson($data, $status = 200, $encodingOptions = 0)
{
$body = $this->getBody();
$body->rewind();
$body->write(json_encode($data, $encodingOptions));
return $this->withStatus($status)->withHeader('Content-Type', 'application/json;charset=utf-8');
}
... so you'll need to do it yourself. The bare minimum is a call to json_last_error().
Because it's attempting to encode html into strings in JSON, the "
characters in the html are probably causing the issue. Try including the option JSON_HEX_QUOT as the 3rd parameter.
$response->withJson($resp,201,JSON_HEX_QUOT);
This will escape the "
character in the html to the unicode literal \u0022
, preventing clashes.
What you likely want.
slim/php-view
or slim/twig-view
Using JSON is silly since you still have to server side render the HTML, then package it up into a JSON format. Doing this is generally a bad idea since JSON in the spec will only accept UTF-8 and there's no way around that.