Reputation: 1813
/* generate csv content */
while($res = mysql_fetch_assoc($query)) {
/* If two or more columns of the result have the same field names, the last column will take precedence. */
for($i=0; $i<mysql_num_fields($query);$i++) {
$data = $res[mysql_field_name($query,$i)];
$data = trim( preg_replace( '/\s+/', ' ', $data ) );
echo "\"".$data."\";";
}
echo "\r\n";
}
The following code intends to remove extra whitespace or newline characters and generate a csv file. My problem is that on some workstations the csv file is displayed correctly and on other stations it is displayed incorrectly although all stations have the same Regional and Language Settings.
Is there something else I should check out or use a different code for generating proper csv files that cleans hidden spaces or new lines?
I discovered some faulty settings regarding regional and language settings options, although the settings we're the same, in Regional Options > Customise > Numbers > List Separator it was something different from ";" so this explains some of the issues reported.
The fix is to implement proper csv code generator and check workstation configurations.
Upvotes: 0
Views: 172
Reputation: 88647
Try this:
$outfp = fopen('php://output', 'w');
while ($row = mysql_fetch_assoc($query)) {
foreach ($row as &$field) {
$field = preg_replace('/\s+/', ' ', trim($field));
}
fputcsv($outfp, $row, ';');
}
Using fputcsv()
will produce much better output than anything you can write manually, considering many edge cases that your code does not. You can write it to php://output
and it will be the same as echo
ing it.
Upvotes: 3
Reputation: 57774
Instead of
for ($i=0; $i<mysql_num_fields($query); $i++)
it should be
for ($i=0; $i<mysql_num_fields($res); $i++)
to look at the correct number of fields.
Upvotes: 0