I'm trying to create a tab delimited file with PHP and having some troubles. Basically my tabs, and line breaks ie \t
and \n
end up being printed out instead of converted to what they are supposed to be.
My code is simple:
$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);
What am I doing wrong here?
Instead of writing your own code. You can use fputcsv function
$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);
Use double quotes around \t
and \n
. You can also use PHP_EOL
constant for end of line.
$page_print .= $row['product_id'] . " \t " . $row['product_name'] . " \t " . strip_tags($row['product_content']) . " \t " . $row['product_price'] . PHP_EOL;
You need to append them using double quotes (").
quote from PHP:
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
use double quotes "
instead of single '
$page_print .= $row['product_id'] . " \t " . $row['product_name'] . " \t " . strip_tags($row['product_content']) . " \t " . $row['product_price'] . "\n";
EDIT 1
surely you can also use chr()
$page_print .= $row['product_id'] . chr(9) . $row['product_name'] ;
\t
will be tab symbol in ouput only when using double quotes (" "
) - http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double
精彩评论