PHP HTML String into CSV
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 somethi开发者_JAVA技巧ng - 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 :)
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:
$fp = fopen('php://output', 'w');
$delimiter = ';';
$headers = array('Username', 'Email', 'Date joined', 'Reason for joining');
fputcsv($fp, $headers, $delimiter);
foreach ($users as $user) {
$fields = array($user->...);
fputcsv($fp, $fields, $delimiter);
}
fclose($fp);
you forgot the "\r" for the first echo, supposed to be:
echo 'Username;Email;Date joined;Reason for joining'."\r\n";
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.
精彩评论