1

I'm trying to build a PHP script that gets the weather from a Yahoo API. I succesfully imported the data using:

<?php
     $BASE_URL = "http://query.yahooapis.com/v1/public/yql";
     $yql_query = 'select * from weather.forecast where woeid in (select woeid from geo.places(1) where text="Amsterdam")';
     $yql_query_url = $BASE_URL . "?q=" . urlencode($yql_query) . "&format=json";

    // Make call with cURL
    $session = curl_init($yql_query_url);
    curl_setopt($session, CURLOPT_RETURNTRANSFER,true);
    $json = curl_exec($session);
    // Convert JSON to PHP object
    $phpObj =  json_decode($json);
    echo '<pre>';print_r($phpObj).'<pre>';

    $weather = json_decode(json_encode($phpObj->query->results->channel->item->forecast), True);

?>

I get the following out of $weather when using print_r:

    Array
        ([0] => Array
            (
                [code] => 12
                [date] => 12 Apr 2016
                [day] => Tue
                [high] => 62
                [low] => 48
                [text] => Rain
            )

        [1] => Array
            (
                [code] => 28
                [date] => 13 Apr 2016
                [day] => Wed
                [high] => 60
                [low] => 46
                [text] => Mostly Cloudy
            )

        [2] => Array
            (
                [code] => 28
                [date] => 14 Apr 2016
                [day] => Thu
                [high] => 61
                [low] => 43
                [text] => Mostly Cloudy
            )

        [3] => Array
            (
                [code] => 47
                [date] => 15 Apr 2016
                [day] => Fri
                [high] => 57
                [low] => 48
                [text] => Scattered Thunderstorms
            )
    )

I want to get [high], [low] and [text] from [0], but I can't seem to get them out without causing an error or the result being empty. I've searched for similar problems on Stackoverflow, but none are the same or I just don't understand/can't figure out how to use the answer given.

I was hoping someone here could help me, because I've spent way too many hours trying to solve this.

Thanks in Regard

Hamza Zafeer
  • 2,360
  • 13
  • 30
  • 42
RickyR
  • 81
  • 1
  • 7

1 Answers1

3

You can access the elements from array index 0 like this:

echo $weather[0]['high'];     //output: 62
echo $weather[0]['low'];      //output: 48
echo $weather[0]['text'];     //output: Rain
Black
  • 18,150
  • 39
  • 158
  • 271