我正在尝试用PHP创建一个制表符分隔文件并遇到一些麻烦.基本上我的制表符,和换行符,即\t并\n最终被打印出来,而不是转换成他们应该是.
我的代码很简单:
$sql = 'SELECT * FROM products';
$res = mysql_query($sql);
$page_print = 'id \t title \t description \t price';
while($row = mysql_fetch_array($res)) {
$page_print .= $row['product_id'] . ' \t ' . $row['product_name'] . ' \t ' . strip_tags($row['product_content']) . ' \t ' . $row['product_price'] . '\n';
}
$page_print = sanitize_output($page_print);
$myFile = "products.txt";
$fh = fopen($myFile, 'w');
$stringData = trim($page_print);
fwrite($fh, $stringData);
fclose($fh);
Run Code Online (Sandbox Code Playgroud)
我在这做错了什么?
在\t和周围使用双引号\n.您还可以使用PHP_EOL常量作为行尾.
$page_print .= $row['product_id'] . " \t " . $row['product_name'] . " \t " . strip_tags($row['product_content']) . " \t " . $row['product_price'] . PHP_EOL;
Run Code Online (Sandbox Code Playgroud)
而不是编写自己的代码.您可以使用fputcsv函数
$sql = 'SELECT * FROM products ';
$res = mysql_query($sql);
$myFile = "products.txt";
$fh = fopen($myFile, 'w');
fputcsv($fh, array('id', 'title', 'description', 'price'), "\t");
while($row = mysql_fetch_array($res)) {
fputcsv($fh, $row, "\t");
}
fclose($fh);
Run Code Online (Sandbox Code Playgroud)