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);
有帮助吗?

解决方案

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top