【问题标题】:php youtube json decodephp youtube json解码
【发布时间】:2011-03-20 19:12:04
【问题描述】:

我尝试使用 JSON 解码来获取 youtube API 提要。但是,当我将 JSON 结果粘贴到 http://www.jsonlint.com/ 时,我注意到类似

"media$group": {
  "media$category": [

不幸的是,一些符号被 php 拒绝了。这是我的代码,我试图删除这个$ 符号,但可能没有成功。我该如何解决?

$url = 'http://gdata.youtube.com/feeds/api/videosq=football&orderby=published&v=2&alt=json';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $url);
$body1 = curl_exec($ch);
$body = str_replace('$','', $body1);
curl_close($ch);
$data = json_decode($body);
foreach ($data->feed->entry as $result) { 
...
}

【问题讨论】:

  • json_decode 不受字符串中的$ 影响。您意识到显示的 URL 给出了 Invalid request URI 错误吗?
  • @mario,我想获取媒体描述。如果我忽略$,请使用echo $result->mediagroup->mediadescription;,它会回调Catchable fatal error: Object of class stdClass could not be converted to string in...

标签: php json


【解决方案1】:

您的问题是使用 PHP 标识符来访问内容。这里最简单的解决方案是获取数组而不是对象:

$data = json_decode ( $json , $assoc = true );

这允许访问具有以下内容的字段:

echo $result['media$group']['media$description'];

如果您想保留对象语法,可以使用这个组合:

echo $result->{'media$group'}->{'media$category'};

(但数组在这里更安全。如果格式更改且属性不存在,您不会收到致命错误。)

【讨论】:

    【解决方案2】:

    这项工作:

    <?php
    $url = 'http://gdata.youtube.com/feeds/api/videos?q=football&orderby=published&v=2&alt=json';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    $body1 = curl_exec($ch);
    $body = str_replace('$','', $body1);
    curl_close($ch);
    $data = json_decode($body);
    
    foreach ($data->feed->entry as $result) { 
        var_dump($result);
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2012-03-22
      • 2017-03-26
      • 2013-11-05
      • 2011-09-10
      • 2019-04-14
      • 2017-05-31
      • 2023-03-07
      • 2012-08-18
      相关资源
      最近更新 更多