json_encode()转义正斜杠 [英] json_encode() escaping forward slashes
问题描述
我正在从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?
推荐答案
是否可以禁用它?
is there a way to disable it?
是的,您只需要使用JSON_UNESCAPED_SLASHES
标志.
Yes, you only need to use the JSON_UNESCAPED_SLASHES
flag.
!重要,请先阅读: https://stackoverflow.com/a/10210367/367456(知道您在处理什么-了解您的敌人)
!important read before: https://stackoverflow.com/a/10210367/367456 (know what you're dealing with - know your enemy)
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), "\n";
echo json_encode($url, JSON_UNESCAPED_SLASHES), "\n";
示例输出:
"http:\/\/www.example.com\/"
"http://www.example.com/"
这篇关于json_encode()转义正斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!