First of all, you open the same file three times and only close it once. This is not a major problem but you really should make a habit of finishing/closing what you started. You can skip one of those fopen
by using file_get_contents
:
$content = file_get_contents("products.csv");
Now, str_replace
will replace every occurrence of your string. If, for example, $line_of_text[1]
is "11" and $icc
is "9", other values in the file such as "110" will be affected, thus making the rest of future replacements less and less reliable each loop.
If I'm not mistaken and all you want to do is replace a single cell in each row, here's a suggestion:
Create an empty variable, let's say $new_content
Now, change your loop:
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$line_of_text[1] = $row['quantity']; // change cell value
$new_content .= implode(',', $line_of_text).','; // convert into string with extra
// ',' to avoid merging cells
}
$new_content = trim($new_content, ','); // remove extra ','