Search code examples
phpright-to-leftphpwordbidi

Insert RTL text correctly in PHPWord template


I'm using PHPWord template processor to insert some text in a template.

The word template is formatted LTR as all the labels are English.

Here is the line in the word template:

User Name: ${name}

Here is the PHP line that replaces the value:

$template->setValue('name', $user->name);

The sentence is bidirectional. The label is English (LTR) and the username is always Arabic (RTL).

Here is the generated line of code in document.xml, after unzipping the word file:

<w:r><w:rPr><w:b/><w:bCs/><w:lang w:val="en-US" w:bidi="ar-EG"/></w:rPr><w:t>User Name:</w:t></w:r><w:r><w:rPr><w:lang w:val="en-US" w:bidi="ar-EG"/></w:rPr><w:t xml:space="preserve"> عمرو هشام</w:t><w:tab/></w:r>

The replaced text appears correctly RTL in LibreOffice, but appears LTR (reversed) in Microsoft Word.

What can I do to make it appear correctly (RTL) in Microsoft Word ?


Solution

  • you just did the wrong action in the first place correcting the PHPword to work with UTF-8 strings.
    according to this there are two ways to fix PHPword and i tried both. the right one is this:

    On line 150, of Shared/String.php:

    Replace

    public static function IsUTF8($value = '') {
        return utf8_encode(utf8_decode($value)) === $value;
    }
    

    With

    public static function IsUTF8($value = '') {
        return mb_check_encoding($value, "UTF-8");
    }
    

    Then, if you do

    $ grep -rn "utf8_encode" .
    

    On the project root, you will find all lines where utf8_encode is used. You will see lines like

    $linkSrc = utf8_encode($linkSrc); //$linkSrc = $linkSrc;
    
    $givenText = utf8_encode($text); //$givenText = $text;
    

    You can simply remove the utf8_encode as shown in the comments.