search
HomePHP FrameworkYIIWhat to do if the csv file exported by yii2 is garbled?

What to do if the csv file exported by yii2 is garbled?

Jan 13, 2020 pm 03:10 PM
yiiGarbled characters

What to do if the csv file exported by yii2 is garbled?

yii exports the CSV code as follows:

/**
 * 导出csv
 * @author yhdsir
 * @param array    $parameter header 表头
 * @param array    $parameter data   数据
 * @param string   $filename         导出名字
 */
public function export($parameter, $filename = '')
{
    if (empty($filename)) {
        $filename = date('Y-m-d_H-i-s');
    }

    $filename = str_replace(array('"', "'", ' ', ','), '_', $filename) . '.csv';

    if (is_array($parameter)) {
        header('Content-Type: application/vnd.ms-excel');
        header('Cache-Control: max-age=0');
        header("Content-Disposition: attachment;filename={$filename}");
        $fp = fopen('php://output', 'w');
        //fwrite($fp, chr(0xEF) . chr(0xBB) . chr(0xBF));  // 添加 BOM
        if (!empty($parameter['header']) && is_array($parameter['header'])) {
            foreach ($parameter['header'] as $i => $v) {
                // CSV的Excel支持GBK编码,一定要转换,否则乱码 
                // $head[$i] = iconv('utf-8', 'gbk', $v); 
                $parameter['header'][$i] = iconv('utf-8', 'gb2312//TRANSLIT//IGNORE', $v);
            }
            // 将数据通过fputcsv写到文件句柄 
            fputcsv($fp, $parameter['header']);
        }
        if (isset($parameter['data'])) {
            foreach ($parameter['data'] as $row) {
                foreach ($row as $i => $v) {
                    $row[$i] = iconv('utf-8', 'gb2312//TRANSLIT//IGNORE', $v);
                }
                fputcsv($fp, $row);
            }
        }
        fclose($fp);

        return true;
    }
    throw new \yii\web\HttpException(500, "Not a valid parameter!");
}

iconv - The string is converted according to the required character encoding

Instructions

iconv ( string $in_charset , string $out_charset , string $str ) : string

Convert string str from in_charset to out_charset.

Parameters

in_charset: Input character set.

out_charset: Output character set.

str: ​​The string to be converted.

Return value: Returns the converted string, or returns FALSE on failure.

Recommended learning: yii tutorial

The above is the detailed content of What to do if the csv file exported by yii2 is garbled?. For more information, please follow other related articles on the PHP Chinese website!

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
Key Skills for Yii Development: Building Robust Web ApplicationsKey Skills for Yii Development: Building Robust Web ApplicationsMay 14, 2025 am 12:03 AM

TobuildrobustwebapplicationswithYii,mastertheseskills:1)MVCarchitectureforstructuringapplications,2)ActiveRecordforefficientdatabaseoperations,3)WidgetsystemforreusableUIcomponents,4)Validationandsecuritymeasures,5)Cachingforperformanceoptimization,a

What Skills Are Required to Become a Successful Yii Developer?What Skills Are Required to Become a Successful Yii Developer?May 13, 2025 am 12:01 AM

TobecomeasuccessfulYiideveloper,youneed:1)PHPmastery,2)understandingofMVCarchitecture,3)Yiiframeworkproficiency,4)databasemanagementskills,5)front-endknowledge,6)APIdevelopmentexpertise,7)testinganddebuggingcapabilities,8)versioncontrolproficiency,9)

Yii Developers: Common ErrorsYii Developers: Common ErrorsMay 12, 2025 am 12:04 AM

ThemostcommonerrorsinYiiframeworkare"UnknownProperty","InvalidConfiguration","ClassNotFound",and"ValidationErrors".1."UnknownProperty"errorsoccurwhenaccessingnon-existentproperties;ensurepropertiesexi

Yii Developer: Most recquired skills in EuropeYii Developer: Most recquired skills in EuropeMay 11, 2025 am 12:02 AM

The key skills that European Yii developers need to possess include: 1. Yii framework proficiency, 2. PHP proficiency, 3. Database management, 4. Front-end skills, 5. RESTful API development, 6. Version control system, 7. Testing and debugging, 8. Security knowledge, 9. Agile methodology, 10. Soft skills, 11. Localization and internationalization, 12. Continuous learning, these skills make developers stand out in the European market.

Yii: Is the community still active?Yii: Is the community still active?May 10, 2025 am 12:03 AM

Yes,theYiicommunityisstillactiveandvibrant.1)TheofficialYiiforumremainsaresourcefordiscussionsandsupport.2)TheGitHubrepositoryshowsregularcommitsandpullrequests,indicatingongoingdevelopment.3)StackOverflowcontinuestohostYii-relatedquestionsandhigh-qu

Is it easy to migrate a Laravel Project to Yii?Is it easy to migrate a Laravel Project to Yii?May 09, 2025 am 12:01 AM

Migratingalaravel Projecttoyiiishallingbutachieffable WITHIEFLEFLANT.1) Mapoutlaravel component likeroutes, Controllers, Andmodels.2) Translatelaravel's SartisancommandeloequentTooyii's giiandetiverecordeba

Essential Soft Skills for Yii Developers: Communication and CollaborationEssential Soft Skills for Yii Developers: Communication and CollaborationMay 08, 2025 am 12:11 AM

Soft skills are crucial to Yii developers because they facilitate team communication and collaboration. 1) Effective communication ensures that the project is progressing smoothly, such as through clear API documentation and regular meetings. 2) Collaborate to enhance team interaction through Yii's tools such as Gii to improve development efficiency.

Laravel MVC : What are the best benefits?Laravel MVC : What are the best benefits?May 07, 2025 pm 03:53 PM

Laravel'sMVCarchitectureoffersenhancedcodeorganization,improvedmaintainability,andarobustseparationofconcerns.1)Itkeepscodeorganized,makingnavigationandteamworkeasier.2)Itcompartmentalizestheapplication,simplifyingtroubleshootingandmaintenance.3)Itse

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

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools