Phpword Plug-in export Word file Chinese garbled problem processing scheme _php skills

Source: Internet
Author: User
Tags autoloader mixed phpword

A recent project has been developed to export Word documents using PHP technology, comparing several scenarios, starting with the activex/com components that come with Microsoft Office, For example, Word.Application, the advantage of this approach is the high format compatibility, you can generate a pure Doc Word2003 format documents, the disadvantage of a comparison of resources (call will start a WINWORD.EXE process), not suitable for web multiuser access to use Second, PHP is the most of the Web development technology is running on the Linux server, of course, can not use the technology under Windows, platform portability and poor compatibility.

The second way to build word is to generate a word-compatible Web page format, and then open it in Word, which is generally weird, after all, the file format is HTML and the format compatibility is poor, but the advantage of this approach is that it saves server resources and can quickly generate The final scenario is today's protagonist, using Phpword to generate Word2007 (docx) format documents, now basically Microsoft Office Word 2003 versions are compatible with this format, for the 2003 version, You only need to download and install a compatible format package (download address), you can also 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 pack.

OK, let me introduce you to Phpword, you can download and get more information about the project by visiting the project home page.

I am in the process of using the main problem of Chinese garbled, combined with the guidance of the online great God, through the following way to solve such problems, I hope to help.

1. Increase East Asian font support

Open and edit the path/writer/word2007/base.php file content, probably on line No. 349 (the number of rows will change with the version) probably added within the function _writetextstyle:

$objWriter->writeattribute (' W:eastasia ', $font)
For example, my modified fragment is basically the following:

Font
if ($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 problem

Edit phpword/template.php, find code $replace = Utf8_encode ($replace), delete or comment out this line of code, add $replace = Iconv (' GBK ', ' utf-8 ', $replace ); For example, the code should read as follows:

 /**
 * Set a Template value
 * 
 * @param mixed $search
 * @param mixed $replace/public
function Set Value ($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 add this line
  }
 
  $this->_documentxml = Str_replace ($search, $replace, $this->_documentxml);



The method is invoked as follows:

$document->setvalue (' Template ', iconv (' Utf-8 ', ' gb2312//ignore ', ' Chinese '));

The above code mainly solves the problem of the template, the following same reason, solve the problem of section add text, find code $giventext = Utf8_encode ($text), 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 $STYLEPARAGR APh
 * @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 line above
  $text = new Phpword_section_text ($givenText, $styleFont, $styleParagraph);
  $this->_elementcollection[] = $text;
  return $text;
}

The call mode is the same as the template call above, which is not listed here.

Toss up so much, suddenly found there is another version of the Phpword, project class name slightly different, subordinate to the Phpoffice/phpword,github Project address (document). This version of the Phpword content richer, support more functions (including line spacing, indentation and first line indentation, etc.), and finally I also take this version of the Phpword, it is noteworthy that these two versions of the Phpword API interface on the basic consistent, can be universal. However, some APIs are not recommended in the Phpoffice/phpword, such as createsection need to be changed to addsection, in addition to the use of this version of the Phpword do not need to do anything like the above to do any Chinese support, more convenient.

These two Phpword projects are officially provided with more detailed examples and documentation, which is not covered here. The last hint is: In the template mode loadtemplate, only use SetValue and other template operation methods, can not add paragraphs or paragraph changes. This is slightly inconvenient.

For Phpoffice/phpword I provide a simple example for reference (more official examples, of course):

Require_once ' phpoffice/phpword/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\phpword ();
 
$PHPWordHelper = New\phpoffice\phpword\shared\font (); $PHPWord->setdefaultfontname (' imitation ');   Global Font $PHPWord->setdefaultfontsize (16);
The global font size is number 3rd//Set the properties of the document, which can be seen in the right-click property of the document, or omit these steps $properties = $PHPWord->getdocumentproperties ();  $properties->setcreator (' John '); Founder $properties->setcompany (' a company '); The company $properties->settitle (' xxx document '); Title $properties->setdescription (' http://wangye.org '); Description $properties->setlastmodifiedby (' Dick ');   Last modified $properties->setcreated (Time ());   $properties->setmodified (Time ()) created; Modify Time//Add number 3rd imitation font to ' fangsong16pt ' left below using $PHPWord->addfontstyle (' fangsong16pt ', Array (' NAMe ' => ' imitation ', ' size ' =>16);
  Add paragraph styles to ' normal ' for use $PHPWord->addparagraphstyle (' normal ', array (' Align ' => ' both ', ' SpaceBefore ' => 0, ' SpaceAfter ' => 0, ' spacing ' => $PHPWordHelper->pointsizetotwips (2.8), ' lineheight ' => 1.19,//Line spacing ' Inde
 
Ntation ' => Array (//First line indent ' Firstline ' => $PHPWordHelper->pointsizetotwips (32))); Section style: 3.5 cm, 3.8 cm, left 3 cm, right 3 cm, footer 3 cm//Note here cm (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,//page number starting from 1 ' footerheight ' => $PHPWordHel
 
Per->centimetersizetotwips (3),); $section = $PHPWord->addsection ($sectionStyle); Add a section//the following sentence is the input document content, note that here we have just added//font style FANGSONG16PT and paragraph styles normal $section->addtext (' document content ', ' fangsong16pt ', ' normal '); $section->addtextbreak (1);
A new blank paragraph $objWriter = iofactory::createwriter ($PHPWord, ' Word2007 '); $objWriter->save ('/path/to/file ');

 Save to/path/to/file Path

Summarize

1, use the template Word to generate word Chinese garbled solution: Open phpword/template.php file, find $replace = Utf8_encode ($replace); change it to $replace =iconv (' GBK ', ' Utf-8 ', $replace); Can.

2, directly generate Word document, call AddText object when Chinese garbled solution: Open phpword/section.php file, find $giventext = Utf8_encode ($text); change it to $giventext = Iconv (' GBK ', ' utf-8 ', $text);

3, seemingly other methods are similar to the resolution.

4, note that php file using GBK Oh. Anyway, my display is in Chinese. Looking for a long time on the Internet, research for a half-day to be done.

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.