I’m trying to increase the readability of my code by creating additional functions but splitting get_current_weather_data() function causes the following error:
Fatal error: Call to a member function children() on a non-object in C:\xampp\htdocs\Twinz\src\weather.php on line 37
Line 37 has to be the final curly brace after return $weather; and this error has only occurred after creating a separate function for get_city(). I can move it back easy enough but I want to know:
Is it not possible to split this function up and what is the general opinion. Is what I’m trying to do pointless?
This function is pulling in a Yahoo XML weather feed which I process and output the data I require; which happens to be, the city, the temperature and the current conditions.
<?php
function get_current_weather_data() {
// Get XML data from source
$feed = file_get_contents("http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f");
// Check to ensure the feed exists
if (!$feed) {
die('Weather not found! Check feed URL');
}
$xml = new SimpleXmlElement($feed);
get_city();
// Pull temperature
$weather['temp'] = $xml->channel->item->children('yweather', TRUE)->condition->attributes()->temp;
echo $weather['temp'] . "<br />";
// Pull current conditions
$weather['conditions'] = $xml->channel->item->children('yweather', TRUE)->condition->attributes()->text;
echo $weather['conditions'] . "<br />";
return $weather;
}
get_city() function:
function get_city() {
// Pull city
$weather['city'] = $xml->channel->children('yweather', TRUE)->location->attributes()->city;
echo $weather['city'] . "<br />";
}
This is a simple scoping and code design problem, nothing really to do with SimpleXML or XML.
You use
$xmland$weatherin yourget_city()function, but it has no access to any variable$xmlor$weather, nor any way to get that data back out!Rewrite like so: