I have a piece of php code that exports data from mysql to excel. even using
utf-8 for charset, Persian(arabic) are saved weird and they are not recognizable.
If you can help me I will be grateful.
<?php
$con=mysqli_connect("localhost","root","","myDB");
$SQL = mysqli_query($con,"SELECT * FROM view1");
$header = '';
$result ='';
$exportData = mysql_query ($SQL ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $exportData );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $exportData , $i ) . "\t";
}
while( $row = mysql_fetch_row( $exportData ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$result .= trim( $line ) . "\n";
}
$result = str_replace( "\r" , "" , $result );
if ( $result == "" )
{
$result = "\nNo Record(s) Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=export.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$result";
?>
Php native support for this is not that good.
Have you tried php-gd-farsi?
include('php-gd-farsi-master/FarsiGD.php');
$gd = new FarsiGD();
// Create a 300x100 image
$im = imagecreatetruecolor(300, 100);
$red = imagecolorallocate($im, 0xFF, 0x00, 0x00);
$black = imagecolorallocate($im, 0x00, 0x00, 0x00);
// Make the background red
imagefilledrectangle($im, 0, 0, 299, 99, $red);
// Path to our ttf font file
//$font_file = './Vera.ttf';
$font_file = './cour.ttf';
// Draw the text 'PHP Manual' using font size 13
$text = imagecreatetruecolor(200, 60);
imagefilledrectangle($text, 0, 0, 200, 60, $red);
$str = '**ماه**';
$tx = $gd->persianText($str, 'fa', 'normal');
imagefttext($text, 24, 10, 10, 50, $black, $font_file,$tx );
$im = $text;
// Output image to the browser
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
Related
I'm trying to display a captcha image using simple-php-captcha.php .It's working fine on my local but on the net it doesn't show the captcha image and I think it's because of my url structure.
The url of the page is like this http://test.org/v245/some-url and when I check the captcha image src , It's Look like this src="/simple-php-captcha.php?_CAPTCHA&t=0.11252600+1451561363".
I have tried this http://test.org/simple-php-captcha.php?_CAPTCHA&t=0.11252600+1451561363 But it doesn't make the captcha image .
What's the problem ? Should I change something in htaccess ?
UPDATE:
This is the code of simple-php-captcha.php:
<?php
//
// A simple PHP CAPTCHA script
//
// Copyright 2013 by Cory LaViska for A Beautiful Site, LLC
//
// See readme.md for usage, demo, and licensing info
//
function simple_php_captcha($config = array()) {
// Check for GD library
if( !function_exists('gd_info') ) {
throw new Exception('Required GD library is missing');
}
$bg_path = dirname(__FILE__) . '/backgrounds/';
$font_path = dirname(__FILE__) . '/fonts/';
// Default values
$captcha_config = array(
'code' => '',
'min_length' => 5,
'max_length' => 5,
'backgrounds' => array(
$bg_path . '45-degree-fabric.png',
$bg_path . 'cloth-alike.png',
$bg_path . 'grey-sandbag.png',
$bg_path . 'kinda-jean.png',
$bg_path . 'polyester-lite.png',
$bg_path . 'stitched-wool.png',
$bg_path . 'white-carbon.png',
$bg_path . 'white-wave.png'
),
'fonts' => array(
$font_path . 'times_new_yorker.ttf'
),
'characters' => 'ABCDEFGHJKLMNPRSTUVWXYZabcdefghjkmnprstuvwxyz23456789',
'min_font_size' => 28,
'max_font_size' => 28,
'color' => '#666',
'angle_min' => 0,
'angle_max' => 10,
'shadow' => true,
'shadow_color' => '#fff',
'shadow_offset_x' => -1,
'shadow_offset_y' => 1
);
// Overwrite defaults with custom config values
if( is_array($config) ) {
foreach( $config as $key => $value ) $captcha_config[$key] = $value;
}
// Restrict certain values
if( $captcha_config['min_length'] < 1 ) $captcha_config['min_length'] = 1;
if( $captcha_config['angle_min'] < 0 ) $captcha_config['angle_min'] = 0;
if( $captcha_config['angle_max'] > 10 ) $captcha_config['angle_max'] = 10;
if( $captcha_config['angle_max'] < $captcha_config['angle_min'] ) $captcha_config['angle_max'] = $captcha_config['angle_min'];
if( $captcha_config['min_font_size'] < 10 ) $captcha_config['min_font_size'] = 10;
if( $captcha_config['max_font_size'] < $captcha_config['min_font_size'] ) $captcha_config['max_font_size'] = $captcha_config['min_font_size'];
// Use milliseconds instead of seconds
srand(microtime() * 100);
// Generate CAPTCHA code if not set by user
if( empty($captcha_config['code']) ) {
$captcha_config['code'] = '';
$length = rand($captcha_config['min_length'], $captcha_config['max_length']);
while( strlen($captcha_config['code']) < $length ) {
$captcha_config['code'] .= substr($captcha_config['characters'], rand() % (strlen($captcha_config['characters'])), 1);
}
}
// Generate HTML for image src
$image_src = substr(__FILE__, strlen( realpath($_SERVER['DOCUMENT_ROOT']) )) . '?_CAPTCHA&t=' . urlencode(microtime());
$image_src = '/' . ltrim(preg_replace('/\\\\/', '/', $image_src), '/');
$_SESSION['_CAPTCHA']['config'] = serialize($captcha_config);
return array(
'code' => $captcha_config['code'],
'image_src' => $image_src
);
}
if( !function_exists('hex2rgb') ) {
function hex2rgb($hex_str, $return_string = false, $separator = ',') {
$hex_str = preg_replace("/[^0-9A-Fa-f]/", '', $hex_str); // Gets a proper hex string
$rgb_array = array();
if( strlen($hex_str) == 6 ) {
$color_val = hexdec($hex_str);
$rgb_array['r'] = 0xFF & ($color_val >> 0x10);
$rgb_array['g'] = 0xFF & ($color_val >> 0x8);
$rgb_array['b'] = 0xFF & $color_val;
} elseif( strlen($hex_str) == 3 ) {
$rgb_array['r'] = hexdec(str_repeat(substr($hex_str, 0, 1), 2));
$rgb_array['g'] = hexdec(str_repeat(substr($hex_str, 1, 1), 2));
$rgb_array['b'] = hexdec(str_repeat(substr($hex_str, 2, 1), 2));
} else {
return false;
}
return $return_string ? implode($separator, $rgb_array) : $rgb_array;
}
}
// Draw the image
if( isset($_GET['_CAPTCHA']) ) {
session_start();
$captcha_config = unserialize($_SESSION['_CAPTCHA']['config']);
if( !$captcha_config ){
exit();
}
unset($_SESSION['_CAPTCHA']);
// Use milliseconds instead of seconds
srand(microtime() * 100);
// Pick random background, get info, and start captcha
$background = $captcha_config['backgrounds'][rand(0, count($captcha_config['backgrounds']) -1)];
list($bg_width, $bg_height, $bg_type, $bg_attr) = getimagesize($background);
$captcha = imagecreatefrompng($background);
$color = hex2rgb($captcha_config['color']);
$color = imagecolorallocate($captcha, $color['r'], $color['g'], $color['b']);
// Determine text angle
$angle = rand( $captcha_config['angle_min'], $captcha_config['angle_max'] ) * (rand(0, 1) == 1 ? -1 : 1);
// Select font randomly
$font = $captcha_config['fonts'][rand(0, count($captcha_config['fonts']) - 1)];
// Verify font file exists
if( !file_exists($font) ) throw new Exception('Font file not found: ' . $font);
//Set the font size.
$font_size = rand($captcha_config['min_font_size'], $captcha_config['max_font_size']);
$text_box_size = imagettfbbox($font_size, $angle, $font, $captcha_config['code']);
// Determine text position
$box_width = abs($text_box_size[6] - $text_box_size[2]);
$box_height = abs($text_box_size[5] - $text_box_size[1]);
$text_pos_x_min = 0;
$text_pos_x_max = ($bg_width) - ($box_width);
$text_pos_x = rand($text_pos_x_min, $text_pos_x_max);
$text_pos_y_min = $box_height;
$text_pos_y_max = ($bg_height) - ($box_height / 2);
$text_pos_y = rand($text_pos_y_min, $text_pos_y_max);
// Draw shadow
if( $captcha_config['shadow'] ){
$shadow_color = hex2rgb($captcha_config['shadow_color']);
$shadow_color = imagecolorallocate($captcha, $shadow_color['r'], $shadow_color['g'], $shadow_color['b']);
imagettftext($captcha, $font_size, $angle, $text_pos_x + $captcha_config['shadow_offset_x'], $text_pos_y + $captcha_config['shadow_offset_y'], $shadow_color, $font, $captcha_config['code']);
}
// Draw text
imagettftext($captcha, $font_size, $angle, $text_pos_x, $text_pos_y, $color, $font, $captcha_config['code']);
// Output image
header("Content-type: image/png");
imagepng($captcha);
}
Thanks
I have a number of DBF database files that I would like to convert to CSVs. Is there a way to do this in Linux, or in PHP?
I've found a few methods to convert DBFs, but they are very slow.
Try soffice (LibreOffice):
$ soffice --headless --convert-to csv FILETOCONVERT.DBF
Change the files variable to a path to your DBF files. Make sure the file extension matches the case of your files.
set_time_limit( 24192000 );
ini_set( 'memory_limit', '-1' );
$files = glob( '/path/to/*.DBF' );
foreach( $files as $file )
{
echo "Processing: $file\n";
$fileParts = explode( '/', $file );
$endPart = $fileParts[key( array_slice( $fileParts, -1, 1, true ) )];
$csvFile = preg_replace( '~\.[a-z]+$~i', '.csv', $endPart );
if( !$dbf = dbase_open( $file, 0 ) ) die( "Could not connect to: $file" );
$num_rec = dbase_numrecords( $dbf );
$num_fields = dbase_numfields( $dbf );
$fields = array();
$out = '';
for( $i = 1; $i <= $num_rec; $i++ )
{
$row = #dbase_get_record_with_names( $dbf, $i );
$firstKey = key( array_slice( $row, 0, 1, true ) );
foreach( $row as $key => $val )
{
if( $key == 'deleted' ) continue;
if( $firstKey != $key ) $out .= ';';
$out .= trim( $val );
}
$out .= "\n";
}
file_put_contents( $csvFile, $out );
}
Using #Kohjah's code, here an update of the code using a better (IMHO) fputcsv approach:
// needs dbase php extension (http://php.net/manual/en/book.dbase.php)
function dbfToCsv($file)
{
$output_path = 'output' . DIRECTORY_SEPARATOR . 'path';
$path_parts = pathinfo($file);
$csvFile = path_parts['filename'] . '.csv';
$output_path_file = $output_path . DIRECTORY_SEPARATOR . $csvFile;
if (!$dbf = dbase_open( $file, 0 )) {
return false;
}
$num_rec = dbase_numrecords( $dbf );
$fp = fopen($output_path_file, 'w');
for( $i = 1; $i <= $num_rec; $i++ ) {
$row = dbase_get_record_with_names( $dbf, $i );
if ($i == 1) {
//print header
fputcsv($fp, array_keys($row));
}
fputcsv($fp, $row);
}
fclose($fp);
}
Pls, let someone help me with this code, When I export, it export the file but start with row2, the first row is excluded.it reads like , header, then row2,3,4 till the end of the row.
<?php
require_once("/includes/session.php");
require_once("/includes/db_connection.php");
require_once("/includes/functions.php");
// Table Name that you want
// to export in csv
$ShowTable = "staff_tab";
$today=date("dmY");
$FileName = "StaffRecord".$today.". csv";
$file = fopen($FileName,"w");
$sql = mysqli_query($connection,("SELECT * FROM $ShowTable LIMIT 500"));
$row = mysqli_fetch_assoc($sql);
// Save headings alon
$HeadingsArray=array();
foreach($row as $name => $value){
$HeadingsArray[]=$name;
}
fputcsv($file,$HeadingsArray);
// Save all records without headings
while($row = mysqli_fetch_assoc($sql)){
$valuesArray=array();
foreach($row as $name => $value){
$valuesArray[]=$value;
}
fputcsv($file,$valuesArray);
}
fclose($file);
header("Location: $FileName");
echo "Complete Record saves as CSV in file: <b style=\"color:red;\">$FileName</b>";
?>
Your call to $row = mysqli_fetch_assoc($sql); is pushing the internal pointer forward to row 2. Use mysqli_data_seek($sql, 0); to push it back to the start. http://php.net/manual/en/function.mysql-data-seek.php
...
$sql = mysqli_query($connection,("SELECT * FROM $ShowTable LIMIT 500"));
$row = mysqli_fetch_assoc($sql);
mysqli_data_seek($sql, 0); // return pointer to first row
// Save headings alon
$HeadingsArray=array();
...
maybe this could help as this will include all rows and set headers from the db headers. This would also force download the file without leaving the page.
$export = mysqli_query ($query) or die ( "Sql error : " . mysqli_error( ) );
// extract the field names for header
$fields = mysqli_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$headers = mysqli_fetch_field($export);
$header .= $headers->name. "\t";
}
// export data
while( $row = mysqli_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\nNo Record(s) Found!\n";
}
// allow exported file to download forcefully
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=Something.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
I am trying to generate an XLS file from a table in a MySQL DB, but the Excel file is not properly formatted & given error when the Excel file generated "The file which you are trying to open is in different format than one specified". When the file is opened the data is not properly formatted.
Any ideas what I am missing?
<?php
$host = 'XXXXXXX';
$dbname = 'XXXXXXXX';
$username = 'XXXXXXXX';
$password = 'XXXXXXXX';
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}
function xlsWriteNumber($Row, $Col, $Value) {
echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
echo pack("d", $Value);
return;
}
try {
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
echo "Connected to $dbname at $host successfully.";
$conn = null;
} catch (PDOException $pe) {
die("Could not connect to the database $dbname :" . $pe->getMessage());
}
$q = "SELECT * FROM tablename";
$qr = mysql_query( $q ) or die( mysql_error() );
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-Disposition: attachment;filename=export_".$dbtable.".xls ");
header("Content-Transfer-Encoding: binary ");
xlsBOF();
$col = 0;
$row = 0;
$first = true;
while( $qrow = mysql_fetch_assoc( $qr ) )
{
if( $first )
{
foreach( $qrow as $k => $v )
{
xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
$col++;
}
$col = 0;
$row++;
$first = false;
}
// go through the data
foreach( $qrow as $k => $v )
{
// write it out
xlsWriteLabel( $row, $col, $v );
$col++;
}
// reset col and goto next row
$col = 0;
$row++;
}
xlsEOF();
exit();
I'm not sure about .xls but for outputting a MySQL result as a CSV table the fputcsv function does it without much fuss:
// Clear any previous output
ob_end_clean();
// I assume you already have your $result
$num_fields = mysql_num_fields($result);
// Fetch MySQL result headers
$headers = array();
$headers[] = "[Row]";
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = strtoupper(mysql_field_name($result , $i));
}
// Filename with current date
$current_date = date("y/m/d");
$filename = "MyFileName" . $current_date . ".csv";
// Open php output stream and write headers
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.$filename);
header('Pragma: no-cache');
header('Expires: 0');
echo "Title of Your CSV File\n\n";
// Write mysql headers to csv
fputcsv($fp, $headers);
$row_tally = 0;
// Write mysql rows to csv
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$row_tally = $row_tally + 1;
echo $row_tally.",";
fputcsv($fp, array_values($row));
}
die;
}
use http://phpexcel.codeplex.com/
C'est la meilleur solution pour générer un fichier excel
Vous pouvez même créer plusieurs feuilles dans le fichier et formater les cellules (couleur, police, bordure, ...)
Google translate:
This is the best solution to generate an excel file You can even create multiple sheets in the file and format the cells (color, font, border, ...)
<?php
//download.php page code
//THIS PROGRAM WILL FETCH THE RESULT OF SQL QUERY AND WILL DOWNLOAD IT. (IF YOU HAVE ANY QUERY CONTACT:rahulpatel541#gmail.com)
//include the database file connection
include_once('database.php');
//will work if the link is set in the indx.php page
if(isset($_GET['name']))
{
$name=$_GET['name']; //to rename the file
header('Content-Disposition: attachment; filename='.$name.'.xls');
header('Cache-Control: no-cache, no-store, must-revalidate, post-check=0, pre-check=0');
header('Pragma: no-cache');
header('Content-Type: application/x-msexcel; charset=windows-1251; format=attachment;');
$msg="";
$var="";
//write your query
$sql="select * from tablename";
$res = mysql_query($sql);
$numcolumn = mysql_num_fields($res); //will fetch number of field in table
$msg="<table><tr><td>Sl No</td>";
for ( $i = 0; $i < $numcolumn; $i++ ) {
$msg.="<td>";
$msg.= mysql_field_name($res, $i); //will store column name of the table to msg variable
$msg.="</td>";
}
$msg.="</tr>";
$i=0;
$count=1; //used to print sl.no
while($row=mysql_fetch_array($res)) //fetch all the row as array
{
$msg.="<tr><td>".$count."</td>";
for($i=0;$i< $numcolumn;$i++)
{
$var=$row[$i]; //will store all the values of row
$msg.="<td>".$var."</td>";
}
$count=$count+1;
$msg.="</tr>";
}
$msg.="</table>";
echo $msg; //will print the content in the exel page
}
?>
<?php
//index.php page
$name="any file name";
echo "<a href='download.php?name=".$name."'>Click to download</a>"; //link to download file
?>
Here is simple Excel file generation function, very fast and exactly .xls file.
$filename = "sample_php_excel.xls";
$data = array(
array("User Name" => "Abid Ali", "Q1" => "$32055", "Q2" => "$31067", "Q3" => 32045, "Q4" => 39043),
array("User Name" => "Sajid Ali", "Q1" => "$25080", "Q2" => "$20677", "Q3" => 32025, "Q4" => 34010),
array("User Name" => "Wajid Ali", "Q1" => "$93067", "Q2" => "$98075", "Q3" => 95404, "Q4" => 102055),
);
to_xls($data, $filename);
function to_xls($data, $filename){
$fp = fopen($filename, "w+");
$str = pack(str_repeat("s", 6), 0x809, 0x8, 0x0, 0x10, 0x0, 0x0); // s | v
fwrite($fp, $str);
if (is_array($data) && !empty($data)){
$row = 0;
foreach (array_values($data) as $_data){
if (is_array($_data) && !empty($_data)){
if ($row == 0){
foreach (array_keys($_data) as $col => $val){
_xlsWriteCell($row, $col, $val, $fp);
}
$row++;
}
foreach (array_values($_data) as $col => $val){
_xlsWriteCell($row, $col, $val, $fp);
}
$row++;
}
}
}
$str = pack(str_repeat("s", 2), 0x0A, 0x00);
fwrite($fp, $str);
fclose($fp);
}
function _xlsWriteCell($row, $col, $val, $fp){
if (is_float($val) || is_int($val)){
$str = pack(str_repeat("s", 5), 0x203, 14, $row, $col, 0x0);
$str .= pack("d", $val);
} else {
$l = strlen($val);
$str = pack(str_repeat("s", 6), 0x204, 8 + $l, $row, $col, 0x0, $l);
$str .= $val;
}
fwrite($fp, $str);
}
<?php
ob_end_clean();
$num_fields = mysql_num_fields($result);
$headers = array();
$headers[] = "[Row]";
for ($i = 0; $i < $num_fields; $i++)
$headers[] = strtoupper(mysql_field_name($result , $i));
$current_date = date("y/m/d");
$filename = "MyFileName" . $current_date . ".csv";
$fp = fopen('php://output', 'w');
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.$filename);
header('Pragma: no-cache');
header('Expires: 0');
echo "Title of Your CSV File\n\n";
fputcsv($fp, $headers);
$row_tally = 0;
// Write mysql rows to csv
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
$row_tally = $row_tally + 1;
echo $row_tally.",";
fputcsv($fp, array_values($row));
}
die;
}
?>
I have got problem with encoding while I transferring data from MySQL to .XLS file. Table is in "utf8_czech_ci" and PHP script in UTF-8. I always get characters like "ěščřžýáíé" in bad form like "ěšÄřžýáÃé". There is my script
<?php
mb_http_input("utf-8");
mb_http_output("utf-8");
$dbhost = "XXXXXXXXXXX";
$dbuser = "XXXXXXXXXXX";
$dbpass = "XXXXXXXXXXX";
$dbname = "XXXXXXXXXXX";
$dbtable = $_GET['table'];
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}
$dbc = mysql_connect( $dbhost , $dbuser , $dbpass ) or die( mysql_error() );
mysql_query("set names utf8;");
mysql_select_db( $dbname );
$q = "SELECT * FROM ".$dbtable."";
$qr = mysql_query( $q ) or die( mysql_error() );
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header("Content-type: application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment;filename=export_".$dbtable.".xls ");
header("Content-Transfer-Encoding: binary ");
xlsBOF();
$col = 0;
$row = 0;
$first = true;
while( $qrow = mysql_fetch_assoc( $qr ) )
{
if( $first )
{
foreach( $qrow as $k => $v )
{
xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
$col++;
}
$col = 0;
$row++;
$first = false;
}
foreach( $qrow as $k => $v )
{
xlsWriteLabel( $row, $col, $v );
$col++;
}
$col = 0;
$row++;
}
xlsEOF();
exit();
Thanks for responses ...
An Excel file uses a codepage block to identify the character set being used within the file, but by default it will use the locale codepage. If you want to force UTF-8, then you'll need to write a UTF-8 codepage block as well
$record = 0x0042; // Record identifier
$length = 0x0002; // Number of bytes to follow
$cv = 0x04B0; // The UTF-8 code page
$header = pack('vv', $record, $length);
$data = pack('v', $cv);