我正在研究一种将数据库中的数据导出到文本文件的工具。代码如下:
$query3=mysql_query("SELECT * FROM records WHERE domain_id=".$domainID." AND type='NS' ORDER BY id ASC, name ASC");
while($result3 = mysql_fetch_array($query3))
{
$type=$result3['type'];
$content=$result3['content'];
$result = $result3['name'];
$length = strlen(".".$domainNAME);
$string = substr($result, 0, $length*(-1));
fwrite($fh,$string." IN NS ".$content."\n");
}
所以输出文本文件之一就像:
IN NS ns1.example.net.
team.example.net. IN NS ns1.example.net.
team.example.net. IN NS ns2.example.net.
teamex01.example.net. IN NS ns1.example.net.
teamex01.example.net. IN NS ns2.example.net.
dev.example.net. IN NS ns1.example.net.
dev.example.net. IN NS ns2.example.net.
我想输出如下文件:
IN NS ns1.example.net.
team.example.net. IN NS ns1.example.net.
team.example.net. IN NS ns2.example.net.
teamex01.example.net. IN NS ns1.example.net.
teamex01.example.net. IN NS ns2.example.net.
dev.example.net. IN NS ns1.example.net.
dev.example.net. IN NS ns2.example.net.
我想按栏排列。 IN NS记录应安排在一列中。有没有办法安排文件?
谢谢!
答案 0 :(得分:1)
要执行此操作,您需要预先遍历整个列表,以使用strlen()
获取第一列中文本的最长字符串长度,然后在输出时使用str_pad()
它使它“漂亮”。
尝试这样的事情(粗略概念):
$results = array();
$longestLength = 0;
// loop through the mysql results, store them in a `results`-array and save the longest-name
while($result = mysql_fetch_array($query)) {
$results[] = $result;
if (($strlen = strlen($result['name'])) > $longestLength) $longestLength = $strlen;
}
// loop through all of the results and output with the desired format
foreach ($results as $result) {
echo sprintf("%s\tIN NS %s\n", str_pad($result['name'], $longestLength), $result['content']);
}
旁注(不具体回答):
建议不要在PHP中使用旧的,已弃用的mysql
扩展名,而是使用受欢迎的mysqli
或PDO
扩展名。两者都提供额外的功能,例如预准备语句,并且对SQL注入攻击也更安全!
答案 1 :(得分:0)
在str_pad()
上使用$string
:
$string = str_pad(substr($result, 0, $length*(-1)), 6, ' ', STR_PAD_RIGHT);
这将在该字符串的末尾添加最多六个空格,以确保它是一个统一的长度。
(根据您在上面提供的示例,6
是任意的。您需要查看哪种值最适合您。)