2012-05-03 222 views
0

我将一个参数解析为一个php文件并尝试使用file_get_contents()获取json。 这是我的代码:无法使用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。

因为我neet与json(在js)后工作,我需要一个非转义版本!

有趣的事情是,我的代码工作,例如用如下JSON: http://xkcd.com/847/info.0.json

什么是我的问题吗?

+0

一切都没有转义,这里引号字符串的引号正确地转义了。 –

+0

'json_decode()'为我正确解码该JSON文件,没有问题。 –

+0

但我如何得到json echo'd,以便我可以读取php的结果作为json? –

回答

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; 
} 
?> 
+0

有没有办法只是以正确的json格式“回显”json,以便我的php只是打印出vimeo json所提供的内容? –

+0

您的意思是? '$ json = file_get_contents(...); echo $ json;' – nickb

+1

我添加了正确的头文件,检查更新。 –

1

使用此:

echo json_decode($json); 

编辑:忘了上面。尝试添加:

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

上述

$url = $_GET['url']; 

,看看有没有什么帮助。

+0

不起作用,我现在只是得到“Array”作为结果 –

+0

@PhilippSiegfried是的,'json_decode'会将JSON变成一个PHP数组。你如何解析JS中的JSON? – honyovk

+0

我希望将PHP作为某种代理来防止跨站点脚本编写问题,当我从不同的机器执行ajax调用时! –

0

更好的是,在这里您提供您的JSON使用:

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