且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

文本文件结构(表)

更新时间:2023-01-23 13:58:54

好的,让我们看看如何做到这一点.我将只专注于相关的标题打印和显示格式化的结果.因此,在这种情况下,我们将使用 fprintf 进行打印一些花式格式的文本到我们正在讨论的文件中.所以这基本上是如何做到的:

Okay, let's see how we can do this. I'm just going to focus on the relevant header printing and displaying formatted results. So then, in this case we're going to use fprintf to print some fancy formatted text to our file in question here. So here's basically how will do this:

id   ||   title   ||   keyword

首先,我们需要为这些字段设置一些宽度,以便所有内容都能以一种不错的方式显示出来.我们将每个宽度设置为10:

First off we need to make some widths for these fields so everything shows up in a nice fashion. We'll set a width of 10 for each:

fprintf($fh, "%-10s || %-10s || %-10s\n", "id", "title", "keyword");

%-10s的作用是告诉我们,我们想将一个字符串格式化为10个字符的宽度,如果长度不够,请使用空格填充.您可以将10调整为任意宽度,以获得***效果.结果出来像这样:

What this %-10s does is tell us that we want a string formatted with a width of 10 characters, with spaces used for padding if the length is not enough. You can adjust the 10 to be whatever width you'd like in order to get the best result. The result comes out to something like this:

id         || title      || keyword

接下来,我们打印出分隔线,我只是略微调整了长度,直到它变得相同为止:

Next we print out our divider, which I just tweaked the length a bit until it came out the same:

fprintf($fh, "===================================\n");

然后我们遍历并打印出我们的值:

Then we loop through and print out our values:

while ($row = mysql_fetch_assoc($result)) {
  fwrite($fh, "%-10s || %-10s || %-10s\n" $row['card_id'], $row['title'],  $row['description']);
}

哪个会给我们这样的东西:

Which will give us something like this:

id         || title      || keyword   
===================================
2          || bob        || jones     
2          || bob        || jones     
2          || bob        || jones     
2          || bob        || jones   

就是这样!这是完整的代码供参考:

And that's it! Here is the full code for reference:

<?php
// Make a MySQL Connection
 mysql_connect("mysql4.host.net", "user", "pass") or die(mysql_error()); 
 mysql_select_db("amyadele_test") or die(mysql_error()); 

// Query the database for data
$query = "SELECT card_id,title,description FROM cards";
$result = mysql_query($query);

// Open file for writing
$myFile = "test.txt";
$fh = fopen($myFile, 'w') or die("can't open file");

// Loop through returned data and write (append) directly to file
fprintf($fh, "%-10s || %-10s || %-10s\n", "id", "title", "keyword");
fprintf($fh, "===================================\n");
while ($row = mysql_fetch_assoc($result)) {
  fprintf($fh, "%-10s || %-10s || %-10s\n", $row['card_id'], $row['title'], $row['description']);
}

// Close out the file
fclose($fh);
?>