PHP 在 JSON 中转义 html 字符串

PHP Escaping html string inside a JSON

我将 Slim php 框架与包含复杂 HTML 内容的数据库一起使用,但是在调用 get 方法时 return 是一个错误 json。 这是 return 代码

$response->withJson($resp, 201); 

我也试过 json_encode 但仍然无效:

$response->withJson(json_encode($resp), 201);

我刚刚注意到 JSON returned 末尾缺少'}]',是否内容太长而无法作为字符串传输? 此外,当我调用 var_dump($resp) 时,它会正确显示我的内容

可能是字符编码有问题。你试过这个吗?

json_encode($array, JSON_UNESCAPED_UNICODE)

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

据我所知,Slim 不关心错误检查:

/**
 * 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');
}

...所以你需要自己做。最低要求是调用 json_last_error().

因为它试图将 html 编码为 JSON 中的字符串,所以 html 中的 " 字符可能导致了问题。尝试将选项 JSON_HEX_QUOT 作为第三个参数。

$response->withJson($resp,201,JSON_HEX_QUOT);

这会将 html 中的 " 字符转义为 unicode 文字 \u0022,防止冲突。

您可能想要什么。

  1. 可以使用 slim/php-viewslim/twig-view
  2. 渲染 HTML
  3. 使用 AJAX 拉取 HTML 并将其放置在您的移动应用程序中。

使用 JSON 很愚蠢,因为您仍然需要在服务器端呈现 HTML,然后将其打包成 JSON 格式。这样做通常不是一个好主意,因为规范中的 JSON 将只接受 UTF-8,而且没有办法解决这个问题。

如果您在末尾缺少 }],那么您的其中一个 PHP 文件在开头 <?php.

之前有两个空格(或换行符)

另一个解决方案是将您的 $app->run() 替换为:

$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

希望我们能在下一个版本中进行适当的修复!