Skip to main content

Reusing PHP function to reduce code duplication



I am pulling in weather data from a Yahoo weather RSS feed for both London and New York. I'm trying to reduce code duplication by reusing a PHP file which contains functions for pulling in the weather data.





Below is the function I am calling - get_current_weather_data() . This function goes off to various other functions such at the get_city() and get_temperature() functions.







<?php



function get_current_weather_data() {



// Get XML data from source



include_once 'index.php';

$feed = file_get_contents(if (isset($sourceFeed)) { echo $sourceFeed; });



// Check to ensure the feed exists

if (!$feed) {

die('Weather not found! Check feed URL');

}

$xml = new SimpleXmlElement($feed);



$weather = get_city($xml);

$weather = get_temperature($xml);

$weather = get_conditions($xml);

$weather = get_icon($xml);



return $weather;

}







In my index.php I set the URL for the RSS feed as the variable called $sourceFeed .







<?php



$tabTitle = ' | Home';

$pageIntroductionHeading = 'Welcome to our site';

$pageIntroductionContent = 'Twinz is a website which has been created to bring towns together!

Our goal is to bring communities around the world together, by providing

information about your home town and its twin town around the world. Our

site provides weather, news and background information for London and

one of its twin cities New York.';

$column1Heading = 'Current Weather for New York';

$column2Heading = 'Current Weather for London';

$column3Heading = 'Current Weather for Paris';



$sourceFeed = "http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f";



include_once 'header.php';

include_once 'navigationMenu.php';

include_once 'threeColumnContainer.php';

include_once 'footer.php';



?>







I attempt to call the feed in my get_current_weather_data() function using:







(if (isset($sourceFeed)) { echo $sourceFeed; }).







However, I receive the following error







"Warning: file_get_contents() [function.file-get-contents]: Filename cannot be empty in C:\xampp\htdocs\Twinz2\nyWeather.php on line 10

Weather not found! Check feed URL".







If I replace







(if (isset($sourceFeed)) { echo $sourceFeed; })







with the URL for the feed it works but this will stop me from reusing the code. Am I trying to do the impossible or is my syntax just incorrect?





This isset method works fine where used elsewhere like for example the $tabTitle and $pageIntroductionHeading variables just need for the RSS feed.





Thanks in advance.


Comments

  1. You're attempting to access a global variable $sourceFeed inside your function. Pass it as a parameter to the function instead:

    // Pass $sourceFeed as a function parameter:
    function get_current_weather_data($sourceFeed) {

    // Get XML data from source

    include_once 'index.php';
    $feed = file_get_contents($sourceFeed));

    // Check to ensure the feed exists
    if (!$feed) {
    die('Weather not found! Check feed URL');
    }
    $xml = new SimpleXmlElement($feed);

    $weather = get_city($xml);
    $weather = get_temperature($xml);
    $weather = get_conditions($xml);
    $weather = get_icon($xml);

    return $weather;
    }


    And call the function as:

    $sourceFeed = "http://weather.yahooapis.com/forecastrss?p=USNY0996&u=f";
    $weather = get_current_weather_data($sourceFeed);

    ReplyDelete
  2. Try to make $sourceFeed global like this:

    function get_current_weather_data() {
    global $sourceFeed


    OR

    get_current_weather_data($sourceFeed)

    ReplyDelete
  3. Your issue is a variable scope issue. The variable that goes inside of the function is a new variable that is used only for the function. It will inaccessible once the function is returned/completed. So, you need to let the function know what the value is:

    function get_current_weather_data( $sourceFeed ) { // this tells the function to
    // read that variable when it starts. You also need to pass it when you call the function.

    get_current_weather_data( $sourceFeed );

    // OR
    get_current_weather_data( 'http://myurl.com' );

    ReplyDelete
  4. The problem is in the following line:

    $feed = file_get_contents(if (isset($sourceFeed)) { echo $sourceFeed; });


    it has to be:

    if(isset($sourceFeed)){ $feed = file_get_contents($sourceFeed); }


    And when you call the function, you also have to pass $sourceFeed as function parameter, like that:

    get_current_weather_data($sourceFeed);

    ReplyDelete
  5. isset($sourceFeed) will always return false. you are using it in a local scope whereas you define it in the global scope. please read more on variable scopes at http://tr2.php.net/manual/en/language.variables.scope.php.

    ReplyDelete
  6. I am fairly sure that what you have done there will not even parse. It certainly won't parse in PHP 5.2.

    $feed = file_get_contents(if (isset($sourceFeed)) { echo $sourceFeed; });


    This is not valid. You cannot place an if statement inside a call to a function, and even if that did work, it would not affect the way the function is called.

    You can use a ternary expression:

    $feed = file_get_contents((isset($sourceFeed)) ? $sourceFeed : '');


    ...but even this will not help you here, since you have to pass a filename to file_get_contents() or you will get the error you see.

    Your approach to this is all wrong, rather than including index.php to define your variable, you should pass the variable to the function as an argument. For example:

    function get_current_weather_data($sourceFeed) {

    // Get XML data from source

    $feed = file_get_contents($sourceFeed);

    // Check to ensure the feed exists
    if (!$feed) {
    die('Weather not found! Check feed URL');
    }
    $xml = new SimpleXmlElement($feed);

    $weather = get_city($xml);
    $weather = get_temperature($xml);
    $weather = get_conditions($xml);
    $weather = get_icon($xml);

    return $weather;

    }

    ReplyDelete

Post a Comment

Popular posts from this blog

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.