English 中文(简体)
使用JSON_decode解析PHP中的JSON对象
原标题:Parsing JSON object in PHP using json_decode
  • 时间:2010-10-27 17:05:23
  •  标签:
  • php
  • json

我试图从以JSON格式提供数据的web服务请求天气。我的PHP请求代码没有成功,它是:

$url="http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
echo $data[0]->weather->weatherIconUrl[0]->value;    

这是返回的一些数据。为简洁起见,部分细节已被截断,但保留了对象完整性:

{ "data": 
    { "current_condition": 
        [ { "cloudcover": "31",
            ... } ],  
      "request": 
        [ { "query": "Schruns, Austria",
            "type": "City" } ],
      "weather": 
        [ { "date": "2010-10-27",
            "precipMM": "0.0",
            "tempMaxC": "3",
            "tempMaxF": "38",
            "tempMinC": "-13",
            "tempMinF": "9",
            "weatherCode": "113",
            "weatherDesc": [ {"value": "Sunny" } ],
            "weatherIconUrl": [ {"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png" } ],
            "winddir16Point": "N",
            "winddirDegree": "356",
            "winddirection": "N",
            "windspeedKmph": "5",
            "windspeedMiles": "3" }, 
          { "date": "2010-10-28",
            ... },

          ... ]
        }
    }
}
最佳回答

这似乎有效:

$url =  http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710%22 ;
$content = file_get_contents($url);
$json = json_decode($content, true);

foreach($json[ data ][ weather ] as $item) {
    print $item[ date ];
    print   -  ;
    print $item[ weatherDesc ][0][ value ];
    print   -  ;
    print  <img src="  . $item[ weatherIconUrl ][0][ value ] .  " border="0" alt="" /> ;
    print  <br> ;
}

如果将json_decode的第二个参数设置为true,则会得到一个数组,因此不能使用->;语法。我还建议您安装JSONview Firefox扩展,因此您可以以类似于Firefox显示XML结构的良好格式的树视图查看生成的json文档。这使事情变得更容易。

问题回答

如果您使用以下内容:

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

TRUE返回一个数组而不是一个对象。

试试这个例子

$json =  {"foo-bar": 12345} ;

$obj = json_decode($json);
print $obj->{ foo-bar }; // 12345

http://php.net/manual/en/function.json-decode.php

注意——两个否定就意味着一个肯定。:)

似乎您忘记了[“value”]->;值

echo $data[0]->weather->weatherIconUrl[0]->value;

json解码时,强制它返回一个数组而不是对象。

$data = json_decode($json, TRUE); -> // TRUE

这将返回一个数组,您可以通过提供键来访问这些值。

您必须首先确保您的服务器允许远程连接,以便函数file_get_contents($url)正常工作,大多数服务器出于安全原因禁用此功能。

在编辑代码时(因为轻度强迫症),我注意到天气也是一个列表。你可能应该考虑一下

echo $data[0]->weather[0]->weatherIconUrl[0]->value;

以确保您使用的weatherIconUrl用于正确的日期实例。





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签