PHP - parsing a txt file

后端 未结 9 1816
余生分开走
余生分开走 2020-11-29 18:43

I have a .txt file that has the following details:

ID^NAME^DESCRIPTION^IMAGES
123^test^Some text goes here^image_1.jpg,image_2.jpg
133^hello^some other test^         


        
9条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 19:31

    Use explode() or fgetcsv():

    $values = explode('^', $string);
    

    Or, if you want something nicer:

    $data = array();
    $firstLine = true;
    foreach(explode("\n", $string) as $line) {
        if($firstLine) { $firstLine = false; continue; } // skip first line
        $row = explode('^', $line);
        $data[] = array(
            'id' => (int)$row[0],
            'name' => $row[1],
            'description' => $row[2],
            'images' => explode(',', $row[3])
        );
    }
    

提交回复
热议问题