PHP - parsing a txt file

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


Solution 1:

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

Solution 2:

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

Solution 3:

By far the best and simplest example of this I have come accross is quite simply the file() method.

$array = file("myfile");
foreach($array as $line)
       {
           echo $line;
       }

This will display all the lines in the file, this is also applicable for a remote URL.

Simple and clear.

REF : IBM PHP Parse