search
Homephp教程php手册php提取csv格式文件中的字符串出现的问题及解决办法

php带csv格式的数据要用到fgetcsv()函数。

用这下面的语句

$hd=fopen('test.csv','r');
$buf=fgetcsv($hd,1000,',');
打开一个test.csv格式的文件,文件中的内容以","号分开。

取出的第一行代表自动含义,比如 id,messaget,time等等。

从第二行开始表示具体的数据,比如1,消息,12:00。

if($buf[1]=="some messages") echo "yes";


按理说从第二行开始,这条语句输出的结果应该为yes,但是尝试之后你会发现没有输出。

这是为什么呢?


可以用strlen()函数来比较$buf[1]与“消息”的长度。

比较的结果竟然是不相等。

天啊,怎么会出现这种问题呢?明明第二行$buf[1]取出来的值是“消息”啊,怎么会长度不一样呢?

这与你的csv格式文件的编码方式有关。


怎么解决这个问题呢?

先用php的字符编码检测函数mb_detect_encoding($buf[1],'UTF-8,EUC-CN,ASSII'),

如果取出来的编码格式为“EUC-CN”,那就哟个下面的语句将其转换为utf8的编码格式,

用php的字符转换函数mb_convert_encoding(),$res=mb_convert_encoding($buf[1],'UTF-8','EUC-CN')。

将转换的结果$res与字符串“消息”比较,这时可以发现,它们终于相等了。


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

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 Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool