首页 > 解决方案 > php中的utf8编码

问题描述

我从 html 表单中获取一些数据并使用 PHP 通过电子邮件发送它们。问题是我得到了奇怪的字符,因为用户在表单中写的语言是捷克语。

例如名称Anežka变为Anežka

这是我用于发送电子邮件的 php 代码。

<?php 
if(isset($_POST['submit'])){
    $to_alex = "myemail@honeywell.com"; // this is your Email address
    $first_name = $_POST['fname'];
    $first_name=mb_convert_encoding($first_name, "UTF-8", "ISO-8859-1");
    $last_name = $_POST['lname'];
    $email = $_POST['email'];
    $skola = $_POST['vysoka_skola'];
    $obor = $_POST['obor'];
    $prace = $_POST['prace'];
    $phone_num=$_POST['phone_number'];
    $linkedin=$_POST['linkedin'];
    $oponenta=$_POST['oponenta'];
    $vedouciho=$_POST['vedouciho'];

    $files = $_FILES['myfile']['name'];
    $kategorie = $_POST['kategorie'];
    //echo gettype($files);
    $all_thesis_string="";
    $all_vedouciho_string="";
    for($index=0;$index<count($_FILES['myfile']['name']);$index++){
        $all_thesis_string.=$_FILES['myfile']['name'][$index].","; //create a string with all bachelor attachments of user
    }
    for($index=0;$index<count($_FILES['vedouciho_files']['name']);$index++){
        $all_vedouciho_string.=$_FILES['vedouciho_files']['name'][$index].","; //create a string with all vedouciho attachments of user
    }
    for($index=0;$index<count($_FILES['oponenta_files']['name']);$index++){
        $all_vedouciho_string.=$_FILES['oponenta_files']['name'][$index].","; //create a string with all oponenta attachments of user
    }

    $subject = "Form submission of ".$first_name." ".$last_name;
    $message = "User Details: \n\n Jméno: $first_name \n Příjmení: $last_name \n Email: $email \n Telefon: $phone_num \n Linkedin: $linkedin \n Vysoká škola: $skola \n Studijní obor: $obor \n Odkaz na bakalářskou práci: $prace \n Kategorie: $kategorie \n Posudek oponenta: \n $oponenta \n Posudek vedouciho: \n $vedouciho \n Bakalářská práce: $all_thesis_string \n Vedouciho files: $all_vedouciho_string";
    $headers = "From:" . $first_name;
    mail($to_alex,$subject,$message,$headers);

    echo '<span style="color:#AFA;text-align:center;"><strong>"Přihláška úspěšně odeslána. Děkuji "</strong></span>';
    //include 'upload.php';
    // You can also use header('Location: thank_you.php'); to redirect to another page. 
    }
?>

mb_convert_encoding在最后一次尝试中尝试过,但我仍然有问题。

标签: phpencoding

解决方案


您需要解决程序输入和输出阶段可能出现的问题:

  1. 确保浏览器知道您需要 UTF-8:它需要HTML 中<meta charset="utf-8">某处的标记。<head>否则,在将表单数据发回给您时,它可能会退回到某些遗留编码。

  2. 确保电子邮件客户知道您将 UTF-8 发送给他们。他们也将在没有明确告知他们的情况下回退到遗留编码。尝试将这些标头添加到邮件中:

    Mime-Version: 1.0
    Content-Type: text/plain; charset=utf-8
    Content-Transfer-Encoding: quoted-printable
    
  3. 如果您希望在主题和/或收件人字段中使用 UTF-8,则需要一种单独的引用方式。我建议你看看优秀的 PHPMailer 包,它将为你处理所有这些。


推荐阅读