CodexBloom - Programming Q&A Platform

How to implement guide with json_unescaped_slashes in php 8.1 causing unexpected output in api responses

👀 Views: 3 💬 Answers: 1 📅 Created: 2025-06-05
php json api PHP

I'm optimizing some code but I've been banging my head against this for hours... I'm experiencing an scenario with `json_encode()` in PHP 8.1 where using the `JSON_UNESCAPED_SLASHES` option is not behaving as expected in my REST API responses. I have a situation where I need to return a JSON object that includes URLs, and I want to preserve the slashes in those URLs to ensure they are not escaped. However, it seems that in some cases, the slashes are still being escaped, leading to malformed URLs in the output. Here's a snippet of my code: ```php $data = [ 'image_url' => 'https://example.com/images/photo.jpg', 'website_url' => 'https://example.com', ]; $response = json_encode($data, JSON_UNESCAPED_SLASHES); header('Content-Type: application/json'); echo $response; ``` When I run this code, I expect to see: ```json { "image_url": "https://example.com/images/photo.jpg", "website_url": "https://example.com" } ``` Instead, I’m getting: ```json { "image_url": "https:\/\/example.com\/images\/photo.jpg", "website_url": "https:\/\/example.com" } ``` I’ve tried removing the `JSON_UNESCAPED_SLASHES` option, but that leads to a double escape of the slashes, which is not what I want. I've also checked if there are any middleware or other parts of the application that might be altering the response, but everything seems to be in order. Is there something I am missing here, or could this be a bug in PHP 8.1? Any insight would be greatly appreciated! This is part of a larger API I'm building. Is there a better approach? This is happening in both development and production on CentOS. Thanks for any help you can provide! I'm on Windows 11 using the latest version of Php.