SitePoint Sponsor

User Tag List

Results 1 to 14 of 14
  1. #1
    SitePoint Addict
    Join Date
    Jul 2003
    Location
    Toronto, Ontario
    Posts
    234
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Exclamation Shortening Reused Code?

    Hey guys,

    There is a piece of code I use throughout my site quite a bit. I feel as if the site is slowing down because of the constant repetition of the code.

    So I was wondering if there was anyway to rewrite the code I'm using into a single block instead of constantly re pasting it every time I need to pull some data.

    Code:
    <?
    $use_curl = 0;
    $symbols = "ABX.TO";
    
    $quote = array();
    $url = "http://finance.yahoo.com/d/quotes.csv?s=$symbols&f=l1p2v&e=.csv";
    
    $fcontents = @file($url);
    
    foreach($fcontents as $line) {
    $info = split(",", $line);
    for($i = 0; $i < sizeof($info); $i ++) {
    $info[$i] = trim(str_replace('"', "", $info[$i]));
    }
    $last = $info[0];
    $change = $info[1];
    $volume = $info[2];
    ?>
    <tr>
    	<td class="company"><a href="#">Barrick</a></td>
    	<td><?php echo "{$last}"; ?></td>
    	<td><?php if ($change > 0){ echo "<font color=\"#008800\">{$change}</font>"; } elseif($change < 0){ echo "<font color=\"#c10000\">{$change}</font>"; } else echo "<font color=\"#4e4e4e\">{$change}</font>"; ?></td>
    	<td class="volume"><?php echo "{$volume}"; ?></td>
    </tr>
    <?php flush(); } ?>
    
    CODE REPEATS HERE
    
    <?
    $use_curl = 0;
    $symbols = "BOL.ST";
    
    $quote = array();
    $url = "http://finance.yahoo.com/d/quotes.csv?s=$symbols&f=l1p2v&e=.csv";
    
    $fcontents = @file($url);
    
    foreach($fcontents as $line) {
    $info = split(",", $line);
    for($i = 0; $i < sizeof($info); $i ++) {
    $info[$i] = trim(str_replace('"', "", $info[$i]));
    }
    $last = $info[0];
    $change = $info[1];
    $volume = $info[2];
    ?>
    <tr>
    	<td class="company"><a href="#">Boliden AB</a></td>
    	<td><?php echo "{$last}"; ?></td>
    	<td><?php if ($change > 0){ echo "<font color=\"#008800\">{$change}</font>"; } elseif($change < 0){ echo "<font color=\"#c10000\">{$change}</font>"; } else echo "<font color=\"#4e4e4e\">{$change}</font>"; ?></td>
    	<td class="volume"><?php echo "{$volume}"; ?></td>
    </tr>
    <?php flush(); } ?>
    Any help would be greatly appreciated.

    Thank you,
    Mario
    $ Available For Hire
    Need a website designed or coded? Then feel free to contact me!

    PSP Backgrounds - PSPBG.net || Photoshop Brushes - PSBrushes.net

  2. #2
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Even if you create a handy-dandy function to perform this task for you (which you probably should do anyway), you would still be performing the same task, only under a different guise.

    Does the data from Yahoo really need to be live? If not, why not create a cache? Or possibly create a cron job which runs at set intervals updating a local data source which the script accesses.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  3. #3
    SitePoint Addict
    Join Date
    Jul 2003
    Location
    Toronto, Ontario
    Posts
    234
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey,

    Thank you for the reply. Unfortunately the data has to be live. I'm fairly new with PHP so I'm not too sure about what other options I have, but I will look into a 'cron job' as you suggested.

    Do you know if the script I'm using would slow down a site noticeably? Perhaps if it was being used 10+ times on a single page.

    If anybody else as any suggestions I would love to hear them, I'm open to any method.

    Thank you,
    Mario
    $ Available For Hire
    Need a website designed or coded? Then feel free to contact me!

    PSP Backgrounds - PSPBG.net || Photoshop Brushes - PSBrushes.net

  4. #4
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Does it really have to be live, or can the data be x seconds, minutes old?
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  5. #5
    SitePoint Addict
    Join Date
    Jul 2003
    Location
    Toronto, Ontario
    Posts
    234
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The data can have a 10 to 20 minute delay.
    $ Available For Hire
    Need a website designed or coded? Then feel free to contact me!

    PSP Backgrounds - PSPBG.net || Photoshop Brushes - PSBrushes.net

  6. #6
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Great, well here's how you would go about setting up a local cache of the data you require.

    A cron job is a scheduled task which you can get the server to run at set intervals, you would get your cron job to run the following script...at say 10 minute intervals?

    PHP Code:
    <?php
    $aSymbols 
    = array(
        
    'ABX.TO'
    );
    $aData = array();
    foreach (
    $aSymbols as $sSymbol)
    {
        
    $aData[$sSymbol] = getStockData($sSymbol);
    }
    file_put_contents('stockCache.dat'serialize($aData));

    function 
    getStockData($sSymbol)
    {
        
    $sCSV file_get_contents('http://finance.yahoo.com/d/quotes.csv?s=' $sSymbol '&f=l1p2v&e=.csv');
        list(
    $sLast$sChange$sVolume) = explode(','preg_replace('~[^0-9.,%\\-\\+]~'''$sCSV));
        return array(
    'last' => $sLast'change' => $sChange'volume' => $sVolume);
    }
    ?>
    This would create a local file called stockCache.dat, you would then use that data instead of the data from Yahoo on each page load.

    Something along the lines of....

    PHP Code:
    <?php
    foreach(unserialize(file_get_contents('stockCache.dat')) as $sSymbol => $aStockData)
    {
        echo 
    $aStockData['last'], $aStockData['change'], $aStockData['volume'];
    }
    ?>
    I hope I'm making sense!
    Last edited by AnthonySterling; Jan 22, 2009 at 13:58. Reason: Added RexExp into function to remove erroneous characters.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  7. #7
    SitePoint Addict
    Join Date
    Jul 2003
    Location
    Toronto, Ontario
    Posts
    234
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey,

    Thanks for the code, I gave it a shot but ran into a small error.

    Code:
    Fatal error: Call to undefined function: file_put_contents() in /test.php on line 20
    Line 21 is...

    Code:
    file_put_contents('stockCache.dat', serialize($aData));
    I tried creating the stockCache.dat myself on the server but still got the error. Any idea why I might be running into this issue?

    Thanks again,
    Mario
    $ Available For Hire
    Need a website designed or coded? Then feel free to contact me!

    PSP Backgrounds - PSPBG.net || Photoshop Brushes - PSBrushes.net

  8. #8
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    file_put_contents was only added in PHP 5, if you are running a PHP 4 variant it won't exist.

    Here's an alternative.
    PHP Code:
    <?php
    if (!function_exists('file_put_contents')) {
        function 
    file_put_contents($filename$data) {
            
    $f = @fopen($filename'w');
            if (!
    $f) {
                return 
    false;
            } else {
                
    $bytes fwrite($f$data);
                
    fclose($f);
                return 
    $bytes;
            }
        }
    }
    ?>
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  9. #9
    SitePoint Addict
    Join Date
    Jul 2003
    Location
    Toronto, Ontario
    Posts
    234
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Awesome!

    It works like a charm.

    Just one last quick question if you have a second.

    To put more symbols in the array its...

    Code:
    $aSymbols = array(
        'ABX.TO',
        'ABX.TO',
        'ABX.TO'
    );
    Correct?

    And how would I go about calling a single item from the array?

    Thanks again, your help saved me hours of figuring it out myself.
    $ Available For Hire
    Need a website designed or coded? Then feel free to contact me!

    PSP Backgrounds - PSPBG.net || Photoshop Brushes - PSBrushes.net

  10. #10
    Twitter: @AnthonySterling silver trophy AnthonySterling's Avatar
    Join Date
    Apr 2008
    Location
    North-East, UK.
    Posts
    6,111
    Mentioned
    3 Post(s)
    Tagged
    0 Thread(s)
    Correct-a-mundo!

    PHP Code:
    <?php
    $aStockData 
    unserialize(file_get_contents('stockCache.dat'));
    echo 
    $aStockData['ABX.TO']['change'];
    ?>
    ...and your most welcome, happy to help.
    @AnthonySterling: I'm a PHP developer, a consultant for oopnorth.com and the organiser of @phpne, a PHP User Group covering the North-East of England.

  11. #11
    SitePoint Addict
    Join Date
    Jul 2003
    Location
    Toronto, Ontario
    Posts
    234
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey,

    The code works great!

    Just a quick question...

    Where can I edit the interval at which the file is updated?

    Thanks,
    Mario
    $ Available For Hire
    Need a website designed or coded? Then feel free to contact me!

    PSP Backgrounds - PSPBG.net || Photoshop Brushes - PSBrushes.net

  12. #12
    SitePoint Guru
    Join Date
    Jan 2005
    Location
    heaven
    Posts
    953
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It currently doesn't. You can try to write the file every 10 mins.

    PHP Code:
    // filemtime retrieves the unix timestamp for when a file was last modified
    if((time() - filemtime('stockCahce.dat')) >= 1*60*10)
    {
        
    $aSymbols = array(
            
    'ABX.TO'
        
    );
        
    $aData = array();
        foreach (
    $aSymbols as $sSymbol)
        {
            
    $aData[$sSymbol] = getStockData($sSymbol);
        }
        
    file_put_contents('stockCache.dat'serialize($aData));

    Creativity knows no other restraint than the
    confines of a small mind.
    - Me
    Geekly Humor
    Oh baby! Check out the design patterns on that framework!

  13. #13
    SitePoint Addict
    Join Date
    Jul 2003
    Location
    Toronto, Ontario
    Posts
    234
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the quick answer imaginethis.

    I will implement that into my code.

    If a time is not set what is the default in terms of how often the file is written to?

    Thanks,
    Mario
    $ Available For Hire
    Need a website designed or coded? Then feel free to contact me!

    PSP Backgrounds - PSPBG.net || Photoshop Brushes - PSBrushes.net

  14. #14
    SitePoint Guru
    Join Date
    Jan 2005
    Location
    heaven
    Posts
    953
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Whenever you write to a file the time is set. So when it's created there is a time. Just make sure the file exists and there will always be a last-updated time.

    PHP Code:
    // filemtime retrieves the unix timestamp for when a file was last modified
    if(((time() - filemtime('stockCahce.dat')) >= 1*60*10) ||
         (!
    file_exists('stockCache.dat'))  // check if file exists
    {
        
    $aSymbols = array(
            
    'ABX.TO'
        
    );
        
    $aData = array();
        foreach (
    $aSymbols as $sSymbol)
        {
            
    $aData[$sSymbol] = getStockData($sSymbol);
        }
        
    file_put_contents('stockCache.dat'serialize($aData));

    Creativity knows no other restraint than the
    confines of a small mind.
    - Me
    Geekly Humor
    Oh baby! Check out the design patterns on that framework!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •