Somdeb Mukherjee
Somdeb Mukherjee

Reputation: 5

Php Excel encoding issue

I am converting exporting some database values to excel using phpexcel. When i echo the value everything works fine but when i am trying to export the value to excel for example The Westminster Terrace,Yau Lai Rd
 Hong Kong it just print the same in excel whereas if i echo it prints The Westminster Terrace, Yau Lai Rd , Hong Kong. The database has utf8_general_ci collation. I had used the following code .

foreach ($data as $question) {
    $c = $c + 1;
    //echo $question['their_answer'];
    $objPHPExcel -> setActiveSheetIndex(0) -> setCellValue($x . $d, $question['their_answer']);
$x++;
}

How to print the same in excel column as echoed any idea?
Thanks
Somdeb

Upvotes: 0

Views: 1547

Answers (3)

Thiago Elias
Thiago Elias

Reputation: 939

Maybe you're experiencing problems with the entities eg: 
.

Try to decode the entities using html_entity_decode while running your code like this:

foreach ($data as $question) {
    $c = $c + 1;
    //echo $question['their_answer'];
    $objPHPExcel -> setActiveSheetIndex(0)->setCellValue($x . $d, html_entity_decode($question['their_answer']));
$x++;
}

The reason for this, may be the fact that your database already saved data with the entities encoded, so it will print correctly in the browser when you echo but won't print in the excel file (because he can't understand what those values are)

Let me know if it works.

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212412

That's because Excel isn't HTML and 
 and 
 are HTML Entities (actually encoded carriage return and line feed characters)..... they're nothing more than literal character in a string to Excel. You need to convert them to their UTF-8 character using something like html_entity_decode()

$string = 'The Westminster Terrace,Yau Lai Rd
 Hong Kong';
$string = html_entity_decode($string, ENT_NOQUOTES, 'UTF-8');

You'll probably also want to set the cell to wrap, and autoheight for the row to handle those return characters as well

Upvotes: 2

Mikel Bitson
Mikel Bitson

Reputation: 3627

These characters are HTML entities. Try html_entity_decode, like this:

foreach ($data as $question) {
    $c = $c + 1;
    $objPHPExcel->setActiveSheetIndex(0)->setCellValue($x . $d, html_entity_decode($question['their_answer']));
    $x++;
}

Upvotes: 2

Related Questions