无法使用file_get_contents()以正确的格式获取json

时间:2012-05-03 19:41:21

标签: php json file-get-contents

我将参数解析为php文件并尝试使用file_get_contents()获取json。 这是我的代码:

< ?php
    $url = $_GET['url'];
    $url = urldecode($url);
    $json = file_get_contents($url, true);
    echo($json);
? >

这是被叫网址: http://vimeo.com/api/v2/channel/photographyschool/videos.json

这是我的结果的一部分:

[{"id":40573637,"title":"All For Nothing - \"Dead To Me\" & \"Twisted Tongues\""}]

等等......所以一切都被逃脱了。结果中甚至还有\ n。

由于我后来使用json(在js中)工作,我需要一个非转义版本!

有趣的是,我的代码可以用这个json工作: http://xkcd.com/847/info.0.json

我的问题是什么?

4 个答案:

答案 0 :(得分:1)

使用此:

echo json_decode($json);

编辑:忘记以上内容。尝试添加:

header('Content-Type: text/plain');

上面

$url = $_GET['url'];

看看是否有帮助。

答案 1 :(得分:1)

如果您只想代理/转发响应,那么只需使用正确的Content-Type标头回显它:

<?php
    header('Content-Type: application/json');
    $json = file_get_contents('http://vimeo.com/api/v2/channel/photographyschool/videos.json');
    echo $json;
?>

你必须非常警惕传递的网址,因为它可能导致XSS!

由于API缓慢/资源匮乏,您应该缓存结果或者至少将其保存在会话中,以便在每次页面加载时不重复。

<?php
$cache = './vimeoCache.json';
$url = 'http://vimeo.com/api/v2/channel/photographyschool/videos.json';

//Set the correct header
header('Content-Type: application/json');

// If a cache file exists, and it is newer than 1 hour, use it
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
    echo file_get_contents($cache);
}else{
    //Grab content and overwrite cache file
    $jsonData = file_get_contents($url);
    file_put_contents($cache,$jsonData);
    echo $jsonData;
}
?>

答案 2 :(得分:0)

答案 3 :(得分:0)

更好的是,你在哪里使用json:

json_encode(array(
    "id" => 40573637,
    "title" => 'All For Nothing - "Dead To Me" & "Twisted Tongues"'
));
相关问题