How do I ensure my content is UTF-8 encoded for my data pull scripts?

Modified on Tue, 1 Nov, 2016 at 6:05 PM

Your header must include the content encoding. Client example:


    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

    header('Content-Encoding: UTF-8');

    header("Content-Length: " . $length);

    header('Content-type: text/csv; charset=UTF-8');

    header('Content-Disposition: attachment; filename=agenda.csv');

    echo "\xEF\xBB\xBF"; // UTF-8 BOM




The full data pull script is displayed below: 


<?php

 

$host = 'mysql.server.com'; // MYSQL database host address

$db = 'database'; // MYSQL database name

$user = 'username'; // Mysql Database user

$pass = 'password'; // Mysql Datbase password

 

// Connect to the database

$link = mysql_connect($host, $user, $pass);

mysql_select_db($db);

 

    $csv_terminated = "\n";

    $csv_separator = ",";

    $csv_enclosed = '"';

    $csv_escaped = "\\";

   

   $sql_query = "select * from ATIVSchedule"; // Your SQL Query here

 

    // Gets the data from the database

    $result = mysql_query($sql_query);

    $fields_cnt = mysql_num_fields($result);

 

    $schema_insert = '';

 

    for ($i = 0; $i < $fields_cnt; $i++)

    {

        $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,

            stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;

        $schema_insert .= $l;

        $schema_insert .= $csv_separator;

    } // end for

 

    $out = trim(substr($schema_insert, 0, -1));

    $out .= $csv_terminated;

 

    // Format the data

    while ($row = mysql_fetch_array($result))

    {

        $schema_insert = '';

        for ($j = 0; $j < $fields_cnt; $j++)

        {

            if ($row[$j] == '0' || $row[$j] != '')

            {

 

                if ($csv_enclosed == '')

                {

                    $schema_insert .= $row[$j];

                } else

                {

                    $schema_insert .= $csv_enclosed .

                    str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;

                }

            } else

            {

                $schema_insert .= '';

            }

 

            if ($j < $fields_cnt - 1)

            {

                $schema_insert .= $csv_separator;

            }

        } // end for

 

        $out .= $schema_insert;

        $out .= $csv_terminated;

    } // end while

 

    $length = strlen($out)+3; // +3 for BOM below.


    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

    header('Content-Encoding: UTF-8');

    header("Content-Length: " . $length);

    header('Content-type: text/csv; charset=UTF-8');

    header('Content-Disposition: attachment; filename=agenda.csv');

    echo "\xEF\xBB\xBF"; // UTF-8 BOM

    echo $out;

 

?>