Solution to Chinese garbled characters when the phpword plug-in exports word Files

Source: Internet
Author: User
Tags autoloader phpword
PHPWord is a plug-in that can generate word Documents from related files. However, it is developed by foreigners and does not support gbk. Therefore, garbled characters may occur when exporting words with Chinese characters, the following is an example of PHPWord.

PHPWord is a plug-in that can generate word Documents from related files. However, it is developed by foreigners and does not support gbk. Therefore, garbled characters may occur when exporting words with Chinese characters, the following is an example of PHPWord.

Recently, the development of a project used PHP Technology to export Word documents. We compared several solutions. First, we used ActiveX/COM components that come with Microsoft Office, such as Word. application, the advantage of this method is that the format is highly compatible and can generate a Word2003 document in pure doc format. The disadvantage is that it occupies resources (a WINWORD will be started when a call is made., the platform is portable and has poor compatibility.

The second method to generate a Word is to generate a Word-compatible webpage format and then open it in Word mode. This method is strange in general. After all, the file format is HTML and the format compatibility is poor, however, this method saves server resources and can be quickly generated. The final solution is to generate Word2007 (docx) Documents in PHPWord format, at present, Microsoft Office Versions later than Word 2003 are basically compatible with this format. For version 2003, you only need to download and install a compatible format package () to open such files normally, of course, if you are using the latest version of Office (including but not limited to Office 2007, Office 2010), you do not need to install this format package.

Now, I will introduce PHPWord. You can download it from the project homepage and obtain more information about the project.

I encountered Chinese garbled characters during usage. I used the following methods to solve these problems based on the guidance of the online experts and hoped to help you.

1. Added support for East Asian fonts.

Open and edit the path/Writer/Word2007/Base. php, and add the following content to the approximate function _ writeTextStyle in line 349th (the number of lines may change with the version:

$ ObjWriter-> writeAttribute ('W: eastAsia ', $ font)
For example, my modified snippets are basically as follows:

// Fontif ($ font! = 'Arial') {$ objWriter-> startElement ('W: rFonts '); $ objWriter-> writeAttribute ('W: eastAsia', $ font ); // Add this line $ objWriter-> writeAttribute ('W: ascii ', $ font); $ objWriter-> writeAttribute ('W: hansi', $ font ); $ objWriter-> writeAttribute ('W: cs ', $ font); $ objWriter-> endElement ();}

2. Solve Chinese garbled characters

Edit PHPWord/Template. php, find the code $ replace = utf8_encode ($ replace);, delete or comment out this line of code, add $ replace = iconv ('gbk', 'utf-8 ', $ replace); for example, the Code is changed to the following:

/*** Set a Template value ** @ param mixed $ search * @ param mixed $ replace */public function setValue ($ search, $ replace) {if (substr ($ search, 0, 2 )! = '$ {' & Substr ($ search,-1 )! = '}') {$ Search = '$ {'. $ search. '}';} if (! Is_array ($ replace) {// $ replace = utf8_encode ($ replace); $ replace = iconv ('gbk', 'utf-8', $ replace ); // comment out the above line and add this line} $ this-> _ documentXML = str_replace ($ search, $ replace, $ this-> _ documentXML );}

The call method is as follows:

$ Document-> setValue ('template', iconv ('utf-8', 'gb2312 // IGNORE ', 'Chinese '));

The code above mainly solves the template issue. In the same way, locate the code $ givenText = utf8_encode ($ text); to delete or comment out this line of code, add $ givenText = iconv ('gbk', 'utf-8', $ text);, for example, the Code is as follows:

/*** Add a Text Element ** @ param string $ text * @ param mixed $ styleFont * @ param mixed $ styleParagraph * @ return PHPWord_Section_Text */public function addText ($ text, $ styleFont = null, $ styleParagraph = null) {// $ givenText = utf8_encode ($ text); $ givenText = iconv ('gbk', 'utf-8 ', $ text); // comment out the above line and add this line $ text = new PHPWord_Section_Text ($ givenText, $ styleFont, $ styleParagraph ); $ this-> _ elementCollection [] = $ text; return $ text ;}

The call method is similar to the template call method above.

After so much trouble, I suddenly found another version of PhpWord on the Internet. The project class names are slightly different in Case sensitivity, and are affiliated with PHPOffice/PHPWord and GitHub Project address (document ). PHPWord of this version is richer in content and supports many features (including line spacing, indentation, and first line indentation). Finally, I also adopt PHPWord of this version, it is worth noting that the PHPWord of these two versions are basically the same on the API interface and can be used universally. However, some APIs are not recommended in PHPOffice/PHPWord. For example, you need to change createSection to addSection. In addition, you do not need to modify the PHPWord version that is used to support any modifications in Chinese as above, ease of use.

The two PHPWord projects provide more detailed examples and documents. The last prompt is: loadTemplate in template mode. You can only use the setValue or other template operation methods. You cannot add paragraphs or paragraphs to modify them. This is slightly inconvenient.

For PHPOffice/PHPWord, I provide a simple example for your reference (of course, more official examples ):

Require_once 'phpoffice/PhpWord. php '; // contains the header file use PhpOffice \ PhpWord \ Autoloader; use PhpOffice \ PhpWord \ Settings; use PhpOffice \ PhpWord \ IOFactory; require_once _ DIR __. '/PhpOffice/PhpWord/Autoloader. php '; Autoloader: register (); Settings: loadConfig (); // Create a new PHPWord Object $ PHPWord = new \ PhpOffice \ PhpWord (); $ PHPWordHelper = new \ PhpOffice \ PhpWord \ Shared \ Font (); $ PHPWord-> setDefaultFontName (' '); // The Global Font $ PHPWord-> setDefaultFontSize (16 ); // The Global font size is 3. // you can view the attributes of the document by right-clicking the document. You can also skip these steps: $ properties = $ PHPWord-> getDocumentProperties (); $ properties-> setCreator ('zhang san'); // creator $ properties-> setCompany ('a company '); // company $ properties-> setTitle ('xx document'); // Title $ properties-> setDescription (' http://wangye.org '); // Description $ properties-> setLastModifiedBy ('Li si'); // finally modify $ properties-> setCreated (time ()); // creation time $ properties-> setModified (time ()); // modify the time // Add the No. 3 font to 'fangsong16pt 'and use $ PHPWord-> addFontStyle ('fangsong16pt', array ('name' => 'son ', 'SIZE' => 16); // Add the paragraph style to 'normal' for the following: $ PHPWord-> addParagraphStyle ('normal ', array ('align '=> 'both', 'spacebefore' => 0, 'space' => 0, 'spacing' => $ PHPWordHelper-> pointSizeToTwips (2.8 ), 'lineheight' => 1.19, // line spacing 'indentation' => array (// indent the first line 'firstline' => $ PHPWordHelper-> pointSizeToTwips (32 )))); // Section style: Top 3.5 cm, bottom 3.8 cm, left 3 cm, right 3 cm, footer 3 cm // note the centimeter here (centimeter) to convert to twips unit $ sectionStyle = array ('orientation' => null, 'marginleft' => $ PHPWordHelper-> centimeterSizeToTwips (3 ), 'marginright' => $ PHPWordHelper-> centimeterSizeToTwips (3), 'margintop' => $ PHPWordHelper-> centimeterSizeToTwips (3.5 ), 'marginbottom' => $ PHPWordHelper-> centimeterSizeToTwips (3.8), 'pagenumberingstart' => 1, // The page number starts from 1: 'footerheight' =>$ PHPWordHelper-> centimeterSizeToTwips (3),); $ section = $ PHPWord-> addSection ($ sectionStyle ); // Add a section. // The following sentence indicates the content of the input document, note that the newly added // font style FangSong16pt and paragraph style Normal $ section-> addText ('document content', 'fangsong16pt ', 'normal') are used here '); $ section-> addTextBreak (1); // create a new blank section $ objWriter = IOFactory: createWriter ($ PHPWord, 'word2007 '); $ objWriter-> save ('/path/to/file'); // save it to the/path/to/file path

Summary

1. Use the Template word to generate Chinese garbled characters. Solution: Open phpword/Template. in the PHP file, find $ replace = utf8_encode ($ replace); change it to $ replace = iconv ('gbk', 'utf-8', $ replace.

2. Generate a Word document directly and call the addText object with Chinese garbled characters. Solution: Open phpword/Section. in the PHP file, find $ givenText = utf8_encode ($ text); change it to $ givenText = iconv ('gbk', 'utf-8', $ text.

3. It seems that other methods are similar to the solution.

4. Pay attention to using gbk for PHP files. My display is Chinese. I have been searching for it online for a long time, and I have been studying it for a long time.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.