php
  • json
  • api
  • 2017-01-30 57 views -3 likes 
    -3

    我正在使用OpenWeather API。我将它保存在$jsonobj,但不知道如何访问天气细节。我不知道[]{}如何不同以及它们实际上的含义。来自URL的PHP​​ JSON值

    我的代码是在这里:

    <?php 
        $name_of_city = "mathura"; 
        $request = 'http://api.openweathermap.org/data/2.5/weather?APPID=my_key&q='.$name_of_city; 
        $response = file_get_contents($request); 
        $jsonobj = json_decode($response,true); 
        print_r($jsonobj); 
    ?> 
    

    enter image description here

    +4

    [用PHP解析JSON文件(可能的重复http://stackoverflow.com/questions/ 4343596 /解析-json-file-with-php) –

    +1

    请不要吝惜,请避免将文本信息作为图像发布。图片无法搜索,无法复制和粘贴,并且可访问性差。并且请** _从不___以JPEG形式发布文本图像。这是一个可怕的文字格式。如果您绝对必须发布文字图片,请使用PNG。 – Chris

    回答

    0

    当你做

    json_decode($response,true);

    它转换JSON到数组,所以你可以像下面访问:

    $name_of_city = "mathura"; 
    $request = 'http://api.openweathermap.org/data/2.5/weather?APPID=my_key&q='.$name_of_city; 
    $response = file_get_contents($request); 
    $jsonobj = json_decode($response,true); 
    foreach($jsonobj['weather'] as $weather){ 
        echo $weather['main'] .":". $weather['description'];//Clear:clear sky 
    } 
    
    0

    []代表数组和{}代表对象,所以在你的榜样,你有例子包含了一个名为“天气”对象的数组对象,访问是在PHP之后json_decode你可以这么简单:

    foreach($jsonobj->weather as $weather){ 
        echo "$weather->main : $weather->description"; 
    } 
    
    +0

    它显示错误注意:尝试获取第9行中的C:\ wamp64 \ www \ localite \ index.php中的非对象的属性我只是在这里尝试我的代码<?php \t $ name_of_city =“mathura”; $ request ='http://api.openweathermap.org/data/2.5/weather?APPID=my_key&q='.$name_of_city; $ response = file_get_contents($ request); $ jsonobj = json_decode($ response,true); \t \t \t的foreach(jsonobj- $>天气为$天气) \t { 回声 “$耐候>主:$与天气>描述”; } \t \t > –

    +0

    那是因为你告诉json_decode为您提供一个关联数组,而不是对象,简单地改变json_decode($响应,真正的)?;到json_decode($ response);或使用$ weather ['main']而不是$ weather-> main – mrbm

    相关问题