Read CSV From PHP

来源:互联网 发布:一维数组的表达方式 编辑:程序博客网 时间:2024/05/22 16:40


This time really let myself down. I downloaded two versions of phpExcelReader, one from sourceForge, one from google code. But all the functions failed to parse the Excel data, I traced $data->sheets, and it always was an empty array. 


PHPExcel is much too complicated with its sample code.


Unfortunately, to save the .xsl file as older version didn't help. Finally, save the file as .csv, and use PHP to read that csv file. But one point is that the file format is ANSI by default, so the browser will raise error when parsing the XML output by PHP, had better to convert it ot UTF-8, and in addition of that, to make it more compatible, had better use <![CDATA[]]> to tell the parser to parse some string as normal.

 

<?phpheader("Content-Type: text/xml");echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";echo "<list>\n";output_csv("company-lists.csv");echo "</list>";function output_csv( $csvfile ){setlocale(LC_ALL, "zh_TW.UTF-8");if( !$fp = fopen($csvfile,"r") ){echo "ERROR";exit;}else{$row=0;while($line = fgetcsv($fp)){if($row == 0){// title}else{echo "<company>";echo "<id>".$line[1]."</id>";echo "<engname><![CDATA[".$line[2]."]]></engname>";echo "<chiname><![CDATA[".$line[3]."]]></chiname>";echo "<strokes>".$line[4]."</strokes>";echo "<floor>".$line[5]."</floor>";echo "<room>".$line[6]."</room>";echo "<bussnature><![CDATA[".$line[7]."]]></bussnature>";echo "<decs><![CDATA[".$line[8]."]]></decs>";echo "</company>";}$row=$row+1;}    fclose($fp);  }}?>



REFS:

http://www.java2s.com/Code/Php/Data-Structure/RemovingtheFirstElementofanArraywitharrayshift.htm

http://www.java2s.com/Code/Php/File-Directory/CSV-File.htm

http://www.java2s.com/Code/Php/XML/ManuallyGeneratingMarkup.htm

http://blog.yam.com/wyattkid/article/9281553