本文介绍了json_encode() 转义正斜杠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 Instagram 中提取 JSON:

I'm pulling JSON from Instagram:

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

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

Then parsing variables into a PHP array to restructure the data, then re-encoding and caching the file:

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

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

When I open the cache file all my forward slashes "/" are being escaped:

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

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

I gather from my searches that json_encode() automatically does this...is there a way to disable it?

推荐答案

是的,您只需要使用 JSON_UNESCAPED_SLASHES 标志.

Yes, you only need to use the JSON_UNESCAPED_SLASHES flag.

!important 之前阅读:https://stackoverflow.com/a/10210367/367456a>(知道你在处理什么 - 了解你的敌人)

json_encode($str, JSON_UNESCAPED_SLASHES);

如果您手头没有 PHP 5.4,请选择众多现有函数中的一个并根据您的需要修改它们,例如http://snippets.dzone.com/posts/show/7487(存档副本).

If you don't have PHP 5.4 at hand, pick one of the many existing functions and modify them to your needs, e.g. http://snippets.dzone.com/posts/show/7487 (archived copy).

示例演示

<?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), "
";

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

示例输出:

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

这篇关于json_encode() 转义正斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 04:49