我试图用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);
我在这里做错了什么?
而不是自己编写代码。可以使用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);
在'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;
您需要使用双引号(")追加它们。
quote from PHP:
注意:与双引号和heredoc语法不同,变量和特殊字符的转义序列将不会被扩展出现在单引号字符串中。
用双引号"
代替单引号'
$page_print .= $row['product_id'] . " 't " . $row['product_name'] . " 't " . strip_tags($row['product_content']) . " 't " . $row['product_price'] . "'n";
编辑1
当然你也可以使用chr()
$page_print .= $row['product_id'] . chr(9) . $row['product_name'] ;
't
只有在使用双引号(" "
)时才会在输出中成为制表符- http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.double