• Heim  >  Artikel  >  Backend-Entwicklung  >  PHP读取txt文件的内容并赋值给数组的代码_php技巧

    PHP读取txt文件的内容并赋值给数组的代码_php技巧

    WBOY
    WBOYOriginal
    2016-05-17 09:14:451235Durchsuche

    2010-12-15.txt的文件内容如下:

    复制代码 代码如下:

    01
    02
    03
    04
    05
    06
    07
    08
    09
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    T01
    T02
    T03
    T04
    T05
    T06
    T07
    T08
    T09
    T10
    T11
    T12
    T13
    T14
    T15
    T16

    思路如下:使用file_get_contents()获取txt文件的内容,然后通过explode()把获得的字符串转化为数组。获得数组长度可以使用count()函数。

    PHP Code
    复制代码 代码如下:

    $file = '2010-12-15.txt';
    $content = file_get_contents($file);
    //echo $content;

    $array = explode("\r\n", $content);
    //print_r($array);

    for($i=0; $i〈count($array); $i++)
    {
    echo $array[$i].'〈br /〉';
    }

    关于txt文档中的换行符
    在正则表达式中,有一个\n是newline的意思,又有一个\r是carriage return(就是这个导致了白痴中文翻译"回车")的意思。在处理String或者console输出的时候,无论带上哪个都能换行。

    但是偏偏在txt中,哪个都不是标准的换行,只有合起来的\r\n才是换行(对于整个windows默认的换行来说,都是这样)。

    意思是\r敲个回车,表明这行结束了,光标回到头去,然后再\n下移一行来个新行。

    就因为这个,我用scanner()带正则表达式搜索txt文档时,一度一筹莫展,根本找不到问题在哪。

    关于file_get_contents()
    file_get_contents() 函数把整个文件读入一个字符串中。

    file_get_contents() 函数是用于将文件的内容读入到一个字符串中的首选方法。如果操作系统支持,还会使用内存映射技术来增强性能。
    Stellungnahme:
    Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn