Search code examples
phpmysqlmysqlitwignon-ascii-characters

When passing an array to Twig, words with special characters are disappearing


I can query data from the database use mysqli, output to Twig and create a table, and words with characters with accents(À, Í, etc) are not displayed.

The array can be displayed through a var_dump perfectly. So somewhere in Twig is it going awry.

I have:

  • A database with data in Spanish
  • PHP
  • Silex/Twig
  • A table schema in utf8, with text being displayed correctly.

I have tried:

  • mb_convert_encoding before sending it to Twig
  • convert_encoding('iso-8859', 'UTF-8') in Twig

I am at a loss as to what to do next, nor why it is not working. If anyone knows why the entire word disappears, that would be great.

Template Example:

{% if results %}
<div class="table-container" id="table-container">
    <table class="results-table" id="results-table">
        <thead>
        <tr>
            <th>{{ "First Name"|trans }}</th>
            <th>{{ "Second Name"|trans }}</T></th>
            <th>{{ "First Surname"|trans }}</th>
            <th>{{ "Second Surname"|trans }}</th>
            <th>{{ "Number"|trans }}</th>
            <th>{{ "Type"|trans }}</th>
            <th>{{ "District"|trans }}</th>
            <th>{{ "State"|trans }}</th>
            <th>{{ "City"|trans }}</th>
        </tr>
        </thead>

        <tbody class="results">
        {% for r in results %}
        <tr>
            <td>{{ r.first_name }}</td>
            <td>{{ r.middle_inital }}</td>
            <td>{{ r.surname }}</td>
            <td>{{ r.second_surname}}</td>
            <td>{{ r.number }}</td>
            <td>{{ r.type }}</td>
            <td>{{ r.district }}</td>
            <td>{{ r.state }}</td>
            <td>{{ r.city|capitalize }}</td>
        </tr>
        {% endfor %}
        </tbody>
    </table>
</div>
{% endif %}

Array is passed from a mysqli query to a variable. Text book example.


Solution

  • Short Answer: AddCharset UTF-8 .html .php

    Recap:

    • MySQL/Silex/Twig application has data that is output to table
    • Table data is correct
    • Words with special characters are not being rendered
    • Browser and Database is set the UTF-8

    So, after some poking around, I saw to check the HTTP header being sent. It was set to windows-1252. This was forcing the browser to switch away from Unicode whenever the table was loaded.

    I found a directive to place into .htaccess which would force UTF-8 encoding. AddCharset UTF-8 .html .php forces UTF-8 on all HTML and PHP pages.