doude4924 2014-05-27 03:25
浏览 5
已采纳

来自URL的Json in PHP

I'm trying to display some elements from some json data at the following URL using the following code, but it isn't displaying anything. Any ideas what I'm doing wrong?

<?php 

$url="http://fbclaurel.onthecity.org/plaza/events?format=json";

$data = file_get_contents($url);
$json = json_decode($data);

foreach($json->"global_event" as $row)
{
    foreach($row as $key => $val)
    {
       echo $key . ': ' . $val;
       echo '<br>';
    }
}

?>
  • 写回答

2条回答 默认 最新

  • dongsong8932 2014-05-27 03:31
    关注

    You actually have a syntax error that is probably hidden due to your configured error reporting / display settings. It would be something like this

    PHP Parse error: syntax error, unexpected '"global_event"' (T_CONSTANT_ENCAPSED_STRING), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$'

    When developing, I recommend you always have the following properties in php.ini

    display_errors = On
    error_reporting = E_ALL
    

    Update

    I've just checked the data from that API and it returns an array. Each array entry is an object with a single global_event property that is itself, another object. I imagine you're going to need something like this to iterate...

    $json = json_decode($data, true);
    // the second "true" argument forces an array format result.
    // I find it more appropriate when iterate keys or when keys
    // might be invalid property names.
    
    foreach ($json as $obj) {
        $globalEvent = $obj['global_event'];
    
        // now $globalEvent is an array with keys such as
        // addresses, body, created_at, ending_at, etc.
        // Note that few of these properties are simple, scalar values (like strings),
        // most are arrays themselves
    
        // display example...
        echo 'title: ', htmlspecialchars($globalEvent['title']), '<br>',
             'short_url: ', htmlspecialchars($globalEvent['short_url']), '<br>';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题