php - json_encode() 转义正斜杠

标签 php json

我正在从 Instagram 中提取 JSON:

$instagrams = json_decode($response)->data;

然后将变量解析成PHP数组来重构数据,然后重新编码和缓存文件:

file_put_contents($cache,json_encode($results));

当我打开缓存文件时,我所有的正斜杠“/”都被转义了:

http:\/\/distilleryimage4.instagram.com\/410e7...

我从搜索中收集到 json_encode() 会自动执行此操作...有没有办法禁用它?

最佳答案

is there a way to disable it?

是的,您只需要使用 JSON_UNESCAPED_SLASHES 标志(PHP 5.4+)。

!important read before: https://stackoverflow.com/a/10210367/367456 (know what you're dealing with - know your enemy: DO NOT USE in web/html context - CLI, unless CGI, might be fine thought, if they think they need it in JSON HTTP context for readability purposes, they have a different problem)

json_encode($str, JSON_UNESCAPED_SLASHES);

如果您手头没有 PHP 5.4(您肯定已经声明了上面的警告),请从众多现有函数中选择一个并根据您的需要对其进行修改,例如http://snippets.dzone.com/posts/show/7487 (archived copy) .

Example Demo

<?php
/*
 * Escaping the reverse-solidus character ("/", slash) is optional in JSON.
 *
 * This can be controlled with the JSON_UNESCAPED_SLASHES flag constant in PHP.
 *
 * @link http://stackoverflow.com/a/10210433/367456
 */    

$url = 'http://www.example.com/';

echo json_encode($url), "\n";

echo json_encode($url, JSON_UNESCAPED_SLASHES), "\n";

示例输出:

"http:\/\/www.example.com\/"
"http://www.example.com/"

关于php - json_encode() 转义正斜杠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10210338/

相关文章:

android - 使用通用图像加载器和 JSON 而不是 Constant Class

java - 如何获取 List<JSONObject> 中的每个元素 json = new ArrayList<JSONObject>()

php - 将 MySQL 数据库值分配给 PHP 变量

php set_time_limit() 在 php-fpm 上生成超时

php包括打印 '1'

javascript - 如何使用 jquery 或 php 根据先前选择的响应保持单选按钮的选择?

php - 从数据库中获取趋势帖子 - symfony 查询生成器 - MySQL

javascript - 如何解决 "Access Denied: Invalid token, wrong code"的问题?

javascript - forEach 不是函数 javascript

javascript - 从另一个域获取数据(json格式),无需jsonp