Question

Yahoo has a finance api which allows individuals to obtain current and historical stock information. They have multiple ways of retrieving this information, one of them is by using the Yahoo Query Language and the other is by just straight downloading/reading their .csv (comma separated file) files.

I found a very useful script for reading the csv files via php. However I only seem to be getting the first 9,000 characters or so of the csv file. I've tried playing with the file size to no avail and I'm wondering where exactly I'm being capped and if there is a way around this.

Is php capping me, is yahoo capping me (seems unlikely), or is it just that one can only pass so much information through the http protocol? I welcome any informed comments and really appreciate any constructive criticisms. My code is below:

<?php

// Setup Variables
$requestUrl = "http://ichart.yahoo.com/table.csv?s=GOOG&a=0&b=1&c=2000&d=0&e=31";

// Pull data (download CSV as file)
$filesize=1000000;
$handle = fopen($requestUrl, "r");
$raw = fread($handle, $filesize);
fclose($handle);

echo $raw; //error checking, turns out the $raw is only about 8000 characters long


// Split results, trim way the extra line break at the end
$quotes = explode("\n",trim($raw));


foreach($quotes as $quoteraw) {
$quoteraw = str_replace(", I", " I", $quoteraw);
$quote = explode(",", $quoteraw);

echo $quote[0]."
"; // output the first element of the array, the Company Name
}

?>

EDIT: Will up-vote all constructive advice, thanks so much :)).

Était-ce utile?

La solution 2

$CSV = file_get_contents('http://ichart.yahoo.com/table.csv?s=GOOG&a=0&b=1&c=2000&d=0&e=31');
var_dump($CSV);

^ try this one on for size.

You only fread once. It's only natural you don't get the whole thing. It needs to be read until feof(). You can't expect TCP/IP to delivery your expected buffer size. You say fread() a maximum of ##### bytes but you get in return as much as the server wants to (/ can) send in one strike.

PS: To go full awesome, use cURL! But file_get_contents should do here.

Autres conseils

As it is csv file, use fgetcsv instead.

Sample code from php.net:

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top