PHP HTML 字符串转换为 CSV
绕了一圈,希望有人能纠正我。
通过 PHP 生成 CSV 并使用 MySQL 中的数据。数据是由用户通过 TinyMCE 输入的,因此具有各种“p”标签等,我显然需要删除我可以成功完成的操作,但是即使在删除之后,csv 中的字符串仍然会显示在各种不同的单元格中。
我尝试过使用 strip_tags() 和 preg 匹配“/n”和“/r”以及各种方式来删除换行符,但没有运气,因为它仍然出现在新单元格上。
我在 csv 中使用分号作为分隔符。
我试图从中剥离所有 html 的字符串的示例是 我想加入,因为它看起来很有趣
。仅当它们有多个
标签或其他内容时才会发生这种情况 - 如果字符串只是一行,则不会出现任何问题。
这是我正在使用的 csv 代码:
echo 'Username;Email;Date joined;Reason for joining'."\r\n";
foreach($users as $user) {
$csv_data .= $user->username . ';' . $user->email. ';' . date("d/m/y", $user->time_created) . ';' . $user->reason_for_joining .';'."\r\n";
}
echo $csv_data;
我哪里出错了?
谢谢大家:)
Going around in circles so hopefully someone can put me right.
Generating a CSV through PHP and using my data from MySQL. Data is inputted by the user via TinyMCE so has various "p" tags etc that I obviously need to strip out which I can do successfully, however the string in the csv still gets displayed in various different cells even after being stripped.
I've tried using strip_tags() and preg matching "/n" and "/r" and all sorts to remove line breaks but no luck as it still appears on new cells.
I'm using a semi colon as the seperator in the csv.
An example of a string i'm trying to strip all html from would be<p>I would like to join because it looks fun</p><p> </p><p>Help me.</p>
. It only happens when their is more than one
tag or something - if the string is simply one line, it works no issues.
Heres the csv code i'm using:
echo 'Username;Email;Date joined;Reason for joining'."\r\n";
foreach($users as $user) {
$csv_data .= $user->username . ';' . $user->email. ';' . date("d/m/y", $user->time_created) . ';' . $user->reason_for_joining .';'."\r\n";
}
echo $csv_data;
Where am i going wrong?
Thanks guys :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
CSV 格式的陷阱比人们想象的要多(正如您所经历的)。因此,不要重新发明轮子并使用
fputcsv
,它正确地转义了所有需要转义的内容。fputcsv
期望写入文件,但您可以给它一个假文件来写入,如 此处:The CSV format has more pitfalls than one might imagine (as you are experiencing). Therefore, don't reinvent the wheel and use
fputcsv
, which correctly escapes everything that needs escaping.fputcsv
expects to write to a file, but you can give it a fake file to write to instead, as outlined here:你忘记了第一个回显的“\r”,
应该是:
并且最好在“for”循环之前将 $csv_data 设置为空白。
如果“用户名”、“电子邮件”、“加入原因”中有分号,
该代码将生成格式错误的 csv。
you forgot the "\r" for the first echo,
supposed to be:
and better set $csv_data to blank before the 'for' loop.
and if either 'username', 'email', 'reason_for_joining' has the semicolon,
the code will generate a mal-formed csv.