PHP - parsing a txt file

terrid25 picture terrid25 · Mar 14, 2011 · Viewed 95.9k times · Source

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^image_3456.jpg,image_89.jpg

What I'd like to do, is parse this ad get the values into a more readable format, possibly into an array if possible.

Thanks

Answer

Michiel Pater picture Michiel Pater · Mar 14, 2011

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'] . '<br />';
    echo 'Row ' . $row . ' NAME: ' . $info[$row]['name'] . '<br />';
    echo 'Row ' . $row . ' DESCRIPTION: ' . $info[$row]['description'] . '<br />';
    echo 'Row ' . $row . ' IMAGES:<br />';

    //display images
    $row_images = explode(',', $info[$row]['images']);

    foreach($row_images as $row_image)
    {
        echo ' - ' . $row_image . '<br />';
    }

    echo '<br />';
}

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']);