将 SELECT 查询的结果打印为 PHP 中的预格式化文本? [英] Print results of a SELECT query as preformatted text in PHP?
问题描述
我正在寻找一种简单快捷的方法来将 PHP 中 MySQL SELECT 查询的结果打印为预格式化文本.我想要的是能够将查询对象传递给函数并像运行 SELECT 语句时命令行 MySQL 客户端那样获取记录集的打印输出.
I'm looking for an easy and quick way to print out the results of a MySQL SELECT query in PHP as preformatted text. What I would like is to be able to pass a query object to a function and get a printout of the recordset like the command line MySQL client does when running SELECT statements.
这是我希望它的外观示例(即 ASCII):
Here is an example of how I want it to look (i.e. ASCII):
+----+-------------+
| id | countryCode |
+----+-------------+
| 1 | ES |
| 2 | AN |
| 3 | AF |
| 4 | AX |
| 5 | AL |
| 6 | DZ |
| 7 | AS |
| 8 | AD |
| 9 | AO |
| 10 | AI |
+----+-------------+
它基本上用于通用导入脚本,我正在执行 SELECT 查询并希望向用户显示结果以供确认.
It's basically for a generic import script, I am doing a SELECT query and want to display the results to the user for confirmation.
推荐答案
sprintf 是你的朋友,如果你必须有一个非 HTML 固定宽度的输出.
sprintf is your friend, if you must have a non-HTML fixed width output.
预计到达时间:
//id: integer, max width 10
//code: string max width 2
$divider=sprintf("+%-10s+%-13s+",'-','-');
$lines[]=$divider;
$lines[]=sprintf("|%10s|%13s|",'id','countryCode'); //header
$lines[]=$divider;
while($line=$records->fetch_assoc()) {
//store the formatted output
$lines[]=sprintf("| %10u | %2.2s |", $line['id'],$line['code']);
}
$table=implode("\n",$lines);
echo $table;
如果您想立即打印出来而不是存储结果,请改用 printf
- 相同的语法.有一个合理的 PHP (s)printf 教程 here.
If you want to print out immediately instead of storing the results, use printf
instead- same syntax. There is a reasonable PHP (s)printf tutorial here.
这篇关于将 SELECT 查询的结果打印为 PHP 中的预格式化文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!