删除出现的“、、”从 MySQL 数据库输出 PHP
我使用以下代码将 MySQL 数据库的内容输出到文本文件中:
<?php
$host = 'localhost';
$user = 'myusername';
$pass = 'mypassword';
$db = 'mydbname';
$table = 'mytablename';
$file = 'outputfilename';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
//$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].",";
}
$csv_output .= "\n";
}
//echo $csv_output;
$myFile = "output.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $csv_output;
fwrite($fh, $stringData);
fclose($fh);
exit;
?>
但是我想知道如何用以下代码替换出现的字符串 ",,,"
: ","
在进入文本文件之前。
I am outputting the contents of my MySQL Database into a text file using the below code:
<?php
$host = 'localhost';
$user = 'myusername';
$pass = 'mypassword';
$db = 'mydbname';
$table = 'mytablename';
$file = 'outputfilename';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
//$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].",";
}
$csv_output .= "\n";
}
//echo $csv_output;
$myFile = "output.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $csv_output;
fwrite($fh, $stringData);
fclose($fh);
exit;
?>
However I would like to know how I could replace the occurances of the string ",,,"
with this: ","
before it goes into the text file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不需要
preg_replace()
。一个简单的
str_replace
就足够了。No need for
preg_replace()
.A simple
str_replace
will suffice.问题在于:
如果您得到
,,,,
这意味着某些列没有值。检测这些列,不要将它们包含在 SELECT 语句中。如果您自动(preg_replace、str_replace)将多个逗号更改为一个逗号,那么您就可以很好地损坏 CSV 文件。
problem is in:
if you got
,,,,
it means that some columns has no value. Detect those columns, do not include them inSELECT
statement.if you will automatically (preg_replace, str_replace) change multiple commas to one comma, you are on good way to corrupt CSV file.
使用
preg_replace()
。像这样的东西(未经测试):Use
preg_replace()
. Something like this (untested):添加此代码:
或更改 for 代码:
add this code:
OR change the for code:
str_replace()
http://php.net/str-replace
str_replace()
http://php.net/str-replace