
在使用 PHP 和 Symfony 构建 API 时,我们经常需要返回包含错误信息的 JsonResponse。当错误信息中包含双引号时,例如 "Variable "user" is invalid",直接将其作为 JsonResponse 的消息内容,最终的 JSON 响应可能会包含转义字符 \,导致可读性下降。
<?php
use Symfony\Component\HttpFoundation\JsonResponse;
class ErrTC
{
public function error($codeError, $message, $statusCode): JsonResponse
{
return new JsonResponse([
'code' => $codeError,
'description' => $message
], $statusCode);
}
}
// 示例调用,message 包含双引号
$errTC = new ErrTC();
$response = $errTC->error('AUTH_ERROR', 'Variable "user" is invalid', 401);
echo $response->getContent(); // 输出: {"code":"AUTH_ERROR","description":"Variable \"user\" is invalid"}上述代码中,$response->getContent() 的输出结果为 {"code":"AUTH_ERROR","description":"Variable \"user\" is invalid"},可以看到双引号被转义了。这是因为在 JSON 字符串中,双引号必须使用反斜杠进行转义。
解决方案:使用单引号代替双引号
一个简单的解决方案是使用单引号来包围需要包含在消息中的字符串,这样就不需要进行转义。
<?php
use Symfony\Component\HttpFoundation\JsonResponse;
class ErrTC
{
public function error($codeError, $message, $statusCode): JsonResponse
{
return new JsonResponse([
'code' => $codeError,
'description' => $message
], $statusCode);
}
}
// 示例调用,message 使用单引号
$errTC = new ErrTC();
$response = $errTC->error('AUTH_ERROR', "Variable 'user' is invalid", 401);
echo $response->getContent(); // 输出: {"code":"AUTH_ERROR","description":"Variable 'user' is invalid"}修改后的代码中,$response->getContent() 的输出结果为 {"code":"AUTH_ERROR","description":"Variable 'user' is invalid"},双引号不再需要转义,消息更易于阅读。
总结
在构建 API 返回 JsonResponse 时,如果需要在消息中包含双引号,推荐使用单引号来包围目标字符串,避免转义字符的出现,提高 API 响应的可读性。虽然转义后的双引号在技术上是正确的,但为了更好的用户体验,应该尽量避免。
以上就是如何在 JsonResponse 消息中正确显示双引号的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号