我正在从 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) .
<?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/