简体   繁体   中英

PHP - write to CSV with html special characters

I'm trying to save data to a CSV from source data containing HTML special characters. I've tried every PHP character encoding/decoding trick I could find, nothing seems to work.

Here's a basic example of what I'm attempting without any attempt to handle the special characters. Can anyone show me what I'm doing wrong?

$file = fopen("output.csv", "w");
fwrite($file, '');

$array = array(
    'Casa e Decoração,queimadeestoque20,Zanox',
    'eFácil, Cupom de até 10% de desconto na eFácil, Asus'
);

foreach ($array as $line) {
    $line = explode(',',$line);
    fputcsv($file,$line);
}


fclose($file);

I'm not quite sure why this works but here's the workaround I discovered. If you run the array through html_entity_decode and do another html_entity_decode again on the loop it works. Hope this helps someone.

$file = fopen("output.csv", "w");
fwrite($file, '');

$array = array(
    'Casa e Decoração,queimadeestoque20,Zanox',
    'eFácil, Cupom de até 10% de desconto na eFácil, Asus'
);

$whatever = array();
foreach ($array as $line) {
    $line = html_entity_decode($line);
    $whatever[] = $line;
}

foreach ($whatever as $line) {
    $line = html_entity_decode($line);

    $line = explode(',',$line);
    fputcsv($file,$line);
}

fclose($file);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM