我使用以下命令以csv格式转储sql文件: $ file_path =“/ tmp / app_users.csv”;
$sql = "SELECT 'id','username','name','email',
'phone_number','city',
'batch_code','course_type' UNION ALL
SELECT id, username, name, email,
phone_number, city, batch_code, course_type
FROM users INTO OUTFILE '".$file_path."' ".
"FIELDS TERMINATED BY ','
ENCLOSED BY '\"'
LINES TERMINATED BY '\r\n'";
$db = Zend_Registry::get('db');
$stmt = $db->query($sql, array());
但是users表中的某些字段为null,在csv输出中显示为\ N.我希望它被替换为字符串“NULL”。我尝试使用str_replace,但它在每行之后神秘地插入了一个额外的空行。
答案 0 :(得分:2)
如果FIELDS ESCAPED BY字符为空(在您的查询中),则不转义任何字符,并将NULL输出为NULL,而不是\ N。
所以下面应该给你想要的结果:
$sql = "SELECT 'id','username','name','email',
'phone_number','city',
'batch_code','course_type' UNION ALL
SELECT id, username, name, email,
phone_number, city, batch_code, course_type
FROM users INTO OUTFILE '".$file_path."' ".
"FIELDS TERMINATED BY ','
ENCLOSED BY '\"'
ESCAPED BY ''
LINES TERMINATED BY '\r\n'";
这只是一种方法,如果你需要转义其他字符,你可能不想使用它。