PHP - parsing a txt file

后端 未结 9 1826
余生分开走
余生分开走 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:30

    You can do that easily this way

    $txt_file    = file_get_contents('path/to/file.txt');
    $rows        = explode("\n", $txt_file);
    array_shift($rows);
    
    foreach($rows as $row => $data)
    {
        //get row data
        $row_data = explode('^', $data);
    
        $info[$row]['id']           = $row_data[0];
        $info[$row]['name']         = $row_data[1];
        $info[$row]['description']  = $row_data[2];
        $info[$row]['images']       = $row_data[3];
    
        //display data
        echo 'Row ' . $row . ' ID: ' . $info[$row]['id'] . '
    '; echo 'Row ' . $row . ' NAME: ' . $info[$row]['name'] . '
    '; echo 'Row ' . $row . ' DESCRIPTION: ' . $info[$row]['description'] . '
    '; echo 'Row ' . $row . ' IMAGES:
    '; //display images $row_images = explode(',', $info[$row]['images']); foreach($row_images as $row_image) { echo ' - ' . $row_image . '
    '; } echo '
    '; }

    First you open the text file using the function file_get_contents() and then you cut the string on the newline characters using the function explode(). This way you will obtain an array with all rows seperated. Then with the function array_shift() you can remove the first row, as it is the header.

    After obtaining the rows, you can loop through the array and put all information in a new array called $info. You will then be able to obtain information per row, starting at row zero. So for example $info[0]['description'] would be Some text goes here.

    If you want to put the images in an array too, you could use explode() too. Just use this for the first row: $first_row_images = explode(',', $info[0]['images']);

提交回复
热议问题