---
# System prepended metadata

title: 解決 json_encode 格式化的數據出現反斜杠的問題
tags: [PHP]

---

---
tags: PHP
---

# 解決 json_encode 格式化的數據出現反斜杠的問題

在上傳多個圖片檔案使用json_encode 格式化完成時發現

原先陣列資料：`["/img/store/1635141776.png","/img/store/1635141776.png","/img/store/1635141776.png"]`

陣列路徑被轉換以下
`["\/img\/store\/1635141776.png","\/img\/store\/1635141776.png","\/img\/store\/1635141776.png"]`
只要有" / "就會變成" \\/ "，這樣無法讀取到檔案

可以使用以下兩種解決辦法
`$data = ["/img/store/1635141776.png","/img/store/1635141776.png","/img/store/1635141776.png"]`
1. 使用PHP自帶的參數：JSON_UNESCAPED_SLASHES
`json_encode($data, JSON_UNESCAPED_SLASHES);`

2. 字串替換
`str_replace("\\", "/", json_encode($data))`
