Question

getHistory downloads a CSV file from Yahoo finance API, i am trying to get the CSV file, and insert the symbol infront of each of the entries in the file. After that is done i want to write the CSV file back to $symbol.csv. My data is the way i want it, i just cant seem to write it to a CSV file. What am i doing wrong? Or is there a better way to go about this?

$row = 1;
if (($handle = fopen(getHistory("T","2010-06-1"), "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        if($row = 1){array_unshift($data,"Symbol"); }
        else  { array_unshift($data, "T"); }
        $fp = fopen('t.csv', 'w');
        fputcsv($fp, $data);
        fclose($fp);
        $row++;
    }
}
fclose($handle);
Était-ce utile?

La solution

In your loop, you are opening and closing the file on each iteration. You should open the csv file before the loop, add to it, then close it when the loop is done.

Also, you should use === or == for comparisons.

$row = 1;
if (($handle = fopen(getHistory("T","2010-06-1"), "r")) !== FALSE) {
    // This truncates the file to zero length
    // so, we only need to do this once, before the loop
    $fp = fopen('t.csv', 'w');
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        if($row === 1){array_unshift($data,"Symbol"); }
        else  { array_unshift($data, "T"); }
        fputcsv($fp, $data);
        $row++;
    }
    // Close it once we're all done
    fclose($fp);
}
fclose($handle);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top