Convert HTML to CSV in php?

后端 未结 3 1520
春和景丽
春和景丽 2021-01-13 01:14

I have a html table structure like this;

            
                ID
                

        
3条回答
  •  自闭症患者
    2021-01-13 02:04

    it seems that produced CVS has problems with some MS excel version. according to this page:

    However, certain Microsoft programs (I'm looking at you, Access 97), 
    will fail to recognize the CSV properly unless each line ends with \r\n.
    

    so i modified the code as:

    $td = array();
    foreach( $element->find('td') as $row) {
       $td[] = $row->plaintext;
    }
    fwrite($fp,implode(";",$td)."\r\n");
    

    but says also this:

    Secondly, if the first column heading / value of the CSV file begins with 
    `uppercase `ID, certain Microsoft programs (ahem, Excel 2007) will interpret 
    the file `as` being in the` SYLK format rather than CSV`
    

    So i changed the ID,... to id,... All in all, with lower case 'id' and ';' as delimiter this loaded as expected in MS excel 2003.

    UPDATED:

    i found a way to properly load a UTF8 .csv into excel by adding the BOM signature in the file. In PHP this can be done:

    fwrite($fp,"\xEF\xBB\xBF");
    ...start writing
    

    these 3 characters (1 unicode actually) forces excel and the likes to understand the .csv file AS utf8 and therefore decoding it internally.

    There is another solution without using the BOM but its a kind of hack and not well tested; just create your file as file.txt (notice the .txt, not .csv), forcing excel to ask you about the encoding you want; you choose utf8 and done.

提交回复
热议问题