1

I want to parse a dynamically generated CSV file that is on another server (Yahoo Finance), but from what I've read you can't access content on another server using XMLHTTPRequest, at least not in CSV format.

I've thought of a solution to this problem and I would like to know if this is the "right" way or best practice to do this, as I am relatively new to development. This is what I've come up with using PHP:

<?php
    $symbol = $_GET["s"];

    $path = "http://download.finance.yahoo.com/d/quotes.csv?s=" . $symbol . "&f=sl1d1t1c1ohgv&e=.csv";
    $yahooquote = fopen($path, "r");

    while(!feof($yahooquote))
    {
        $line = fgets($yahooquote, 1000);
        echo $line . "<br />";
    }

    fclose($yahooquote);
?>

This returns an html file which has the lines of the CSV file and then I can use JavaScript/jQuery XMLHTTPRequest to parse it on the client side.

Is this the best way to do this? do you have any ideas/suggestions? Please keep in mind that this has to be fast as it has to run every 10 seconds to update +100 stock quotes. Thanks in advance.

4 Answers 4

3

The problem with this is that its being run over and over again by multiple users of your site.

If you want speed, and to decrease bandwidth and performance then you should do the following:

Create a script thats executed privately by cron every X Seconds, which fetches the csv data from yahoo and stores it locally on your server.

Once that is out the way then when your users check via ajax you can just feed them the local copy.

all the users will be sharing the same cached file and your only ever running once per ten seconds, it will also be handled by another instance so users will see faster responces, you may also want to read about file locking

Also you may want to use cURL on PHP Side and

2
2

Check out the example on this tutorial. They use jQuery to request a Yahoo stock quote (in CSV format) through Ajax, which is exactly what you're looking for.

2

Use cURL it is 5x faster.

function curl($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    return curl_exec($ch);
    curl_close ($ch);
}

$symbol = $_GET["s"];
$csv = "http://download.finance.yahoo.com/d/quotes.csv?s=" . $symbol . "&f=sl1d1t1c1ohgv&e=.csv";

$yahoo = curl($csv);

Now contents of CSV file will be in $yahoo variable, which you can parse or store it on your server (fopen, fwrite, fclose).

1
1

@VerizonW: This tutorial on reading a remote file using PHP covers four methods (including the one you're presently using), I suggest you give it a read to see which method you feel most comfortable with. I tend to prefer using cURL.

1
  • Don't trust PHP tutorials written in ASPX :) jk Dec 24, 2010 at 23:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.