search
HomeBackend DevelopmentPHP Tutorialphp文件中的中文乱码该如何解决

php文件中的中文乱码该如何解决

Jun 23, 2016 pm 01:55 PM
phpChineseGarbled charactersdocumentsolve

下面的文件的注释部分含有部分中文,但是乱码了。各位大神,知道该如何把乱码部分解析成中文吗?
class Database
{
/*****************************************************
** MySQL????????????
*****************************************************/
var $db;
var $seconds;
var $queries;
var $timer      = 0;
var $querytimes = array();
var $duration = '';

public $connectData=true;

/*****************************************************
** ??????,?????????
*****************************************************/
function Database($server = '', $username = '', $password = '', $database = '')
{
global $site_engine_root;
// $this->seconds = $this->currentTime();
if ('' == $server)
{
/*****************************************************
** ????????????????
*****************************************************/
$server   = $GLOBALS['db_host'];
$username = $GLOBALS['db_user'];
$password = $GLOBALS['db_pass'];
$database = $GLOBALS['db_name'];
}
/*****************************************************
** ?????????
*****************************************************/
if (!$this->db = @mysql_pconnect($server, $username, $password))
{
if ($username == 'root' && $database == 'siteengine')
  {
  @header("Location:/install.php");
  }
  else
  {
  $this->connectData=false;
  //$this->error("database connect fail");
  }
}
if ($database&&$this->connectData===true)
{
if($this->version() > '4.1')
{
global $config_charset;
$config_charset = 'utf-8';
if(!$dbcharset && in_array(strtolower($config_charset), array('gbk', 'big5', 'utf-8')))
{
$dbcharset = str_replace('-', '', $config_charset);
}
if($dbcharset)
{
mysql_query("SET NAMES '$dbcharset'");
}
}

if($this->version() > '5.0.1')
{
mysql_query("SET sql_mode=''");
}
$this->selectDb($database);
}
return true;
}

/*****************************************************
** ????????????
*****************************************************/
function disconnect()
{
$result = mysql_close() or $this->error();
return $result;
}

/*****************************************************
** ????????
*****************************************************/
function selectDb($database)
{
global $multidomain,$site_engine_root,$tablepre,$db;
if (@mysql_select_db($database, $this->db))
{
return true;
}
else
{
if ($multidomain==1)
{
$query = $this->query("CREATE DATABASE ".$database);
  @header("Location:/install.php");
                // require $site_engine_root.'lib/query.php';
                // $fp = @fopen($site_engine_root.'data/sql/siteengine.sql', "r");
                // $query=@fread($fp, filesize($site_engine_root.'data/sql/siteengine.sql'));
                // @fclose($fp);
                // if($tablepre!='boka') $query=str_replace("boka_",$tablepre,$query);
                // $sql_query = new query($query);
                // $sql_query->doquery();
  // @header("Location:/index.php");

}
  $this->error("$database database connect error!");
}
}

/*****************************************************
** ???????????Web?????????У????????????????С???Web?????·???true???????????·???false
*****************************************************/
function isWebEnv()
{
if (isset($_SERVER['PHP_SELF']))
{
return true;
}
if (isset($GLOBALS['_SERVER']['PHP_SELF']))
{
return true;
}
return false;
}
/*****************************************************
** ???????????????????
*****************************************************/
function _textConvert($text)
{
if ($this->isWebEnv())              // Web????
{
return nl2br($text);
}
return $text;
}

/*****************************************************
** ?????????
*****************************************************/
function currentTime()
{
list($usec, $sec) = explode(' ', microtime());
$time = (double)$sec + (double)$usec;
return $time;
}

function show()
{
$message = "\n" . 'Processed in '
. ($this->currentTime() - $this->seconds) . ' second(s), '
. $this->queries . ' queries.' . "\n";
// return $this->_textConvert($message);
return $message;
}

/*****************************************************
** ?????????????????????
*****************************************************/
function error($var = false)
{
global $domain,$language,$site_engine_root;
// header('Content-Type: text/html; charset="utf-8"');
// @$error = "

An error was encountered
";
// @$error .="SiteEngine\n".$GLOBALS['l_site']['dberror']."  error in file \"".$_SERVER['PHP_SELF']."\"\n";
// @$error .= $GLOBALS['l_site']['errorinfo'].mysql_errno() . ': ' . mysql_error() . "\n";
if ($var)
{
$error .= "\n" . htmlspecialchars(@$GLOBALS['l_site']['errorsql']) . "\n" . $var . "\n";
}

$error .="
 ";
if ($GLOBALS['sesettings']['system']['errorreport']==1)
{
$errorinfo = mysql_errno().":".rawurlencode(mysql_error());
$time = date("Ymd H:i:s",time());
// @file("http://error.siteengine.net/?domain=$domain&errorinfo=$errorinfo&username=$SESSION[username]&time=$time&language=$language");
}
if (file_exists($site_engine_root.'data/install.lock'))
{
die($this->_textConvert($error));
}
else
{
die($this->_textConvert($error));
// @header("Location:/install.php");
}
// ??????
return $error;

}

/*****************************************************
** ???????sql????
*****************************************************/
function query($sql)
{
global $opendebug,$admincp;
$this->start_timer();
if (($opendebug==1 && $admincp==0) || ($opendebug==2 && $admincp==1))
{
echo ''.$sql.';
';
echo gettotaltime().'
';
// echo $sql.';
';
}
$result = @mysql_query($sql, $this->db) or $this->error($sql);
++$this->queries;// ??????????

$this->querytimes[] = $this->stop_timer();
$lowersql=strtolower($sql);
$lowersql=trim($lowersql);
if(substr($lowersql,0,6) == "update" or substr($lowersql,0,6) == "delete" )
{
//echo "find update";
$affectrows=mysql_affected_rows();
return $affectrows;
}
return $result;
}

/*****************************************************
** ???????sql????
*****************************************************/
function unbufferedQuery($sql)
{

$result = mysql_unbuffered_query($sql, $this->db) or $this->error($sql);
return $result;
}

/*****************************************************
** ????????????????????
*****************************************************/
/*
* $result       ??query()????????
* $fetch_mode   ????????Ч???
* DB_FETCHMODE_ORDERED (default)    ??????????????????
* DB_FETCHMODE_ASSOC                ???????????????????
* DB_FETCHMODE_OBJECT               ?????????????
*/
function fetchRow($result, $fetch_mode = false)
{
//assert('is_resource($result)');
switch ($fetch_mode)
{
case DB_FETCHMODE_OBJECT:
     $row = @mysql_fetch_object($result);//$row->username
     break;
case DB_FETCHMODE_ASSOC:
     $row = @mysql_fetch_assoc($result);//$row['username']
     break;
case DB_FETCHMODE_ORDERED:
default:    // ?????
    $row = @mysql_fetch_row($result);// 0,1,2,3
     break;
}
return $row;
}

}
?>


回复讨论(解决方案)

显然是你打开的编码与文件的实际编码并不一致。

复制出来的是没办法还原的。你要看原始文件,用正确的编码打开
如果用不正确的编码打开后又保存了,基本上就没办法恢复了。

通过编辑器新建文件 编码设置 utf-8 把你文件复制进去,就不乱码。

3楼你试过?你用的是什么编辑器。我新建了一个txt,然后把它设为UTF-8,再把代码放进去,依然乱码。

把你的原始文件放到云盘上

3楼你试过?你用的是什么编辑器。我新建了一个txt,然后把它设为UTF-8,再把代码放进去,依然乱码。


notepad++ 你试试这个编辑器

1.你这个文件可以在别人给你的时候,就已经是乱码了。
2.文件的存储方改成 UTF8,可以使用UE , EditPlus 都可以,直接另存为,编码选UTF8。

好像不可逆了。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to modify array elements in PHP?How to modify array elements in PHP?May 15, 2025 pm 08:21 PM

Methods to modify array elements in PHP include direct assignment and batch modification using functions. 1. For indexed arrays, such as $colors=['red','green','blue'], the second element can be modified by $colors[1]='yellow'. 2. For associative arrays, such as $person=['name'=>'John','age'=>30], the value of age can be modified by $person['age']=31. 3. Use array_map or array_walk functions to modify array elements in batches, such as $numbers=array_map(fun

How to implement hook function in PHP?How to implement hook function in PHP?May 15, 2025 pm 08:18 PM

Implementing hook functions in PHP can be implemented through observer mode or event-driven programming. The specific steps are as follows: 1. Create a HookManager class to register and trigger hooks. 2. Use the registerHook method to register the hook and trigger the hook by the triggerHook method when needed. Hook functions can improve the scalability and flexibility of the code, but pay attention to performance overhead and debugging complexity.

PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment