【问题标题】:Unable to get json in correct format with file_get_contents()无法使用 file_get_contents() 以正确格式获取 json
【发布时间】:2012-05-03 19:41:21
【问题描述】:

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

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

这是调用的 URL: 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

我的问题是什么?

【问题讨论】:

  • 所有内容都没有转义,此处引用字符串的内部引号已正确转义。
  • json_decode() 为我正确解码了 JSON 文件,没问题。
  • 但是我如何得到 json echo'd 以便我可以将 php 的结果读取为 json?

标签: php json file-get-contents


【解决方案1】:

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

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

您必须非常小心传递的 url,因为它可能导致 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;
}
?>

【讨论】:

  • 有没有办法以正确的 json 格式“回显”json,以便我的 php 只是打印出 vimeo json 正在传递的内容?
  • 你的意思是这样的? $json = file_get_contents(...); echo $json;
【解决方案2】:

使用这个:

echo json_decode($json);

编辑:忘记上面的。尝试添加:

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

上面

$url = $_GET['url'];

看看有没有帮助。

【讨论】:

  • @PhilippSiegfried 是的,json_decode 会将 JSON 转换为 PHP 数组。你是如何在你的 JS 中解析 JSON 的?
  • 我希望将 php 作为某种代理,以防止当我从另一台机器进行 ajax 调用时出现跨站点脚本问题!
  • 改用print_r(),也许吧?
  • 然后我得到 Array ( [0] => stdClass Object ( [id] => 40573637 [title] => All For nothing - "Dead To Me" & "Twisted Tongues" ... which也没有有效的 json..
  • @PhilippSiegfried 尝试在$url = $_GET['url']; 上方添加header('Content-Type: text/plain');,如果有帮助的话
【解决方案3】:

你应该使用 json_decode : http://php.net/manual/en/function.json-decode.php

【讨论】:

    【解决方案4】:

    更好的是,您可以在哪里使用 json:

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

    【讨论】:

      猜你喜欢
      • 2016-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多