使用PHP创建制表符分隔文件时遇到问题

wil*_*fun 2 php

我正在尝试用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)

我在这做错了什么?

Mch*_*chl 6

\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)


Wes*_*orp 5

您需要使用双引号(")附加它们.

引用PHP:

注意:与双引号和定界符语法,变量和转义特殊字符序列将不会被替换,当它们发生在单引号的字符串.


M K*_*oen 5

而不是编写自己的代码.您可以使用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)